local extension = Package:new("jy_lord")
extension.extensionName = "jy_heg"
extension.game_modes_whitelist = { 'official_heg_mode', }

local H = require "packages/jy_heg/util"
local U = require "packages/utility/utility"

Fk:loadTranslationTable {
  ["jy_lord"] = "君临天下·奕",
  ["jy"] = "奕",
  ["transform_deputy"] = "变更副将",
}

local dengai = General(extension, "jy__dengai", "wei", 4)
dengai.mainMaxHpAdjustedValue = -1
local tuntian = fk.CreateTriggerSkill {
  name = "jy__tuntian",
  anim_type = "special",
  derived_piles = "jy__dengai_field",
  events = { fk.AfterCardsMove },
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(self) and player.phase == Player.NotActive) then return end
    for _, move in ipairs(data) do
      if move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
            return true
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local judge = {
      who = player,
      reason = self.name,
      pattern = ".|.|spade,club,diamond",
    }
    room:judge(judge)
    if judge.card.suit ~= Card.Heart and room:getCardArea(judge.card.id) == Card.DiscardPile and not player.dead and
        room:askForSkillInvoke(player, self.name, nil, "jy__tuntian_field:::" .. judge.card:toLogString()) then
      player:addToPile("jy__dengai_field", judge.card, true, self.name)
    end
  end,
}
local tuntian_distance = fk.CreateDistanceSkill {
  name = "#jy__tuntian_distance",
  correct_func = function(self, from, to)
    if from:hasSkill(self) then
      return - #from:getPile("jy__dengai_field")
    end
  end,
}
tuntian:addRelatedSkill(tuntian_distance)
local jixi = fk.CreateViewAsSkill {
  name = "jy__jixi",
  anim_type = "control",
  pattern = "snatch",
  relate_to_place = "m",
  expand_pile = "jy__dengai_field",
  enabled_at_play = function(self, player)
    return #player:getPile("jy__dengai_field") > 0
  end,
  enabled_at_response = function(self, player)
    return #player:getPile("jy__dengai_field") > 0
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Self:getPileNameOfId(to_select) == "jy__dengai_field"
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then
      return nil
    end
    local c = Fk:cloneCard("snatch")
    c.skillName = self.name
    c:addSubcard(cards[1])
    return c
  end,
}
local ziliang = fk.CreateTriggerSkill {
  name = "jy__ziliang",
  anim_type = "support",
  relate_to_place = "d",
  events = { fk.Damaged },
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and H.compareKingdomWith(player, target) and not target.dead and
        #player:getPile("jy__dengai_field") > 0
  end,
  on_cost = function(self, event, target, player, data)
    local card = player.room:askForCard(player, 1, 1, false, self.name, true, ".|.|.|jy__dengai_field",
      "#jy__ziliang-card::" .. target.id, "jy__dengai_field")
    if #card > 0 then
      self.cost_data = card
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    player.room:moveCardTo(self.cost_data, Card.PlayerHand, target, fk.ReasonGive, self.name, "jy__dengai_field", true,
      player.id)
  end,
}
dengai:addSkill(tuntian)
dengai:addSkill(jixi)
dengai:addSkill(ziliang)
Fk:loadTranslationTable {
  ["jy__dengai"] = "邓艾",
  ["#jy__dengai"] = "矫然的壮士",

  ["jy__tuntian"] = "屯田",
  [":jy__tuntian"] = "当你于回合外失去牌后，你可判定：若结果不为<font color='red'>♥</font>，你可将弃牌堆里的此判定牌置于武将牌上（称为“田”）。你至其他角色的距离-X（X为“田”数）。",
  ["jy__jixi"] = "急袭",
  [":jy__jixi"] = "主将技，此武将牌上的单独阴阳鱼个数-1。你可将一张“田”当【顺手牵羊】使用。",
  ["jy__ziliang"] = "资粮",
  [":jy__ziliang"] = "副将技，当与你势力相同的角色受到伤害后，你可将一张“田”交给其。",

  ["jy__dengai_field"] = "田",
  ["jy__tuntian_field"] = "屯田：将%arg置于武将牌上（称为“田”）",
  ["#jy__ziliang-card"] = "资粮：你可将一张“田”交给 %dest",

  ["$jy__tuntian1"] = "留得良田在，何愁不破敌？",
  ["$jy__tuntian2"] = "击鼓于此，以致四方。",
  ["$jy__ziliang1"] = "兵，断不可无粮啊。",
  ["$jy__ziliang2"] = "吃饱了，才有力气为国效力。",
  ["$jy__jixi1"] = "谁占到先机，谁就胜了。",
  ["$jy__jixi2"] = "哪里走！！",
  ["~jy__dengai"] = "君不知臣，臣不知君。罢了……罢了！",
}

local caoang = General(extension, "jy__caoang", "wei", 4)
caoang:addCompanions("jy__dianwei")
local jy__kangkai = fk.CreateTriggerSkill {
  name = "jy__kangkai",
  anim_type = "support",
  events = { fk.TargetConfirmed },
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.card.trueName == "slash" and
        (target == player or player:distanceTo(target) == 1) and
        player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local prompt = (player.id == data.to) and "#jy__kangkai-self" or "#jy__kangkai-invoke::" .. data.to
    return player.room:askForSkillInvoke(player, self.name, nil, prompt)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(data.to)
    player:drawCards(1, self.name)
    if player == to or player:isNude() or to.dead then return end
    local cards = room:askForCard(player, 1, 1, true, self.name, false, ".", "#jy__kangkai-give::" .. to.id)
    if #cards > 0 then
      room:moveCardTo(cards, Card.PlayerHand, to, fk.ReasonGive, self.name, nil, true, player.id)
      to:showCards(cards)
      local card = Fk:getCardById(cards[1])
      if card.type == Card.TypeEquip and not to.dead and not to:isProhibited(to, card) and not to:prohibitUse(card) and
          table.contains(to:getCardIds("h"), cards[1]) and
          room:askForSkillInvoke(to, self.name, data, "#jy__kangkai-use:::" .. card:toLogString()) then
        room:useCard({
          from = to.id,
          tos = { { to.id } },
          card = card,
        })
      end
    end
  end,
}
caoang:addSkill(jy__kangkai) ---待测试
Fk:loadTranslationTable {
  ["jy__caoang"] = "曹昂",
  ["#jy__caoang"] = "取义成仁",

  ["jy__kangkai"] = "慷忾",
  [":jy__kangkai"] = "每回合限一次，当一名角色成为【杀】的目标后，若你与其的距离不大于1，你可以摸一张牌。若如此做，你先将一张牌交给该角色再令其展示之，若为装备牌，其可使用之。",
  ["#jy__kangkai-invoke"] = "慷忾：你可以摸一张牌，再交给 %dest 一张牌",
  ["#jy__kangkai-self"] = "慷忾：你可以摸一张牌",
  ["#jy__kangkai-give"] = "慷忾：选择一张牌交给 %dest",
  ["#jy__kangkai-use"] = "慷忾：你可以使用%arg",

  ["$jy__kangkai1"] = "典将军，比比看谁杀敌更多！",
  ["$jy__kangkai2"] = "父亲快走，有我殿后！",
  ["~jy__caoang"] = "典将军，还是你赢了……",
}

local lidian = General(extension, "jy__lidian", "wei", 3)
lidian:addCompanions("jy__yuejin")
local xunxun = fk.CreateTriggerSkill {
  name = "jy__xunxun",
  anim_type = "control",
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Draw
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local ret = room:askForArrangeCards(player, self.name, { room:getNCards(4), "Bottom", "Top" }, "#jy__xunxun", true, 0,
      { 4, 2 }, { 0, 2 })
    local top, bottom = ret[2], ret[1]
    for i = #top, 1, -1 do
      table.removeOne(room.draw_pile, top[i])
      table.insert(room.draw_pile, 1, top[i])
    end
    for i = 1, #bottom, 1 do
      table.removeOne(room.draw_pile, bottom[i])
      table.insert(room.draw_pile, bottom[i])
    end
    room:sendLog {
      type = "#GuanxingResult",
      from = player.id,
      arg = #top,
      arg2 = #bottom,
    }
  end,
}
local wangxi = fk.CreateTriggerSkill {
  name = "jy__wangxi",
  events = { fk.Damage, fk.Damaged },
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.from and data.from ~= data.to and
        not (data.from.dead or data.to.dead)
  end,
  on_cost = function(self, event, target, player, data)
    local to = event == fk.Damage and data.to or data.from
    local room = player.room
    if room:askForSkillInvoke(player, self.name, nil, "#jy__wangxi-invoke::" .. to.id) then
      room:doIndicate(player.id, { to.id })
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    room:notifySkillInvoked(player, self.name, event == fk.Damaged and "masochism" or "drawcard")
    local tos = { player.id }
    table.insertIfNeed(tos, data.from.id)
    table.insertIfNeed(tos, data.to.id)
    room:sortPlayersByAction(tos)
    for _, pid in ipairs(tos) do
      local to = room:getPlayerById(pid)
      if not to.dead then
        room:drawCards(to, 1, self.name)
      end
    end
  end
}
lidian:addSkill(xunxun)
lidian:addSkill(wangxi) -------待测试
Fk:loadTranslationTable {
  ["jy__lidian"] = "李典",
  ["#jy__lidian"] = "深明大义",

  ["jy__xunxun"] = "恂恂",
  [":jy__xunxun"] = "摸牌阶段开始时，你可以观看牌堆顶的四张牌，将其中两张牌以任意顺序置于牌堆顶，其余以任意顺序置于牌堆底。",
  ["jy__wangxi"] = "忘隙",
  [":jy__wangxi"] = "当你对其他角色造成伤害后，或当你受到其他角色造成的伤害后，你可以与其各摸一张牌。",
  ["#jy__xunxun"] = "恂恂：选择两张卡牌置于牌堆顶",
  ["#jy__wangxi-invoke"] = "忘隙：你可以与 %dest 各摸一张牌",

  ["$jy__xunxun1"] = "众将死战，非我之功。",
  ["$jy__xunxun2"] = "爱兵如子，胜乃可全。",
  ["$jy__wangxi1"] = "大丈夫，何拘小节。",
  ["$jy__wangxi2"] = "前尘往事，莫再提起。",
  ["~jy__lidian"] = "报国杀敌，虽死犹荣……",
}

local haozhao = General(extension, "jy__haozhao", "wei", 4)
local zhengu = fk.CreateTriggerSkill {
  name = "jy__zhengu",
  anim_type = "drawcard",
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player,
      table.map(player.room:getOtherPlayers(player, false), Util.IdMapper), 1, 1, "#jy__zhengu-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    local num1 = #to:getCardIds(Player.Hand)
    local num2 = #player:getCardIds(Player.Hand)
    if num1 > num2 then
      room:askForDiscard(to, num1 - num2, num1 - num2, false, self.name, false)
    elseif num1 < num2 then
      to:drawCards(num2 - num1, self.name)
    end
  end,
}
haozhao:addSkill(zhengu)
Fk:loadTranslationTable {
  ["jy__haozhao"] = "郝昭",
  ["#jy__haozhao"] = "扣弦的豪将",

  ["jy__zhengu"] = "镇骨",
  [":jy__zhengu"] = "结束阶段，你可以令一名其他角色将手牌数调整至与你相同。",
  ["#jy__zhengu-choose"] = "你可以令一名其他角色将手牌数调整至与你相同。",

  ["$jy__zhengu1"] = "镇守城池，必以骨相拼！",
  ["$jy__zhengu2"] = "孔明计虽百算，却难敌吾镇骨千具！",
  ["~jy__haozhao"] = "镇守陈仓，也有一失。",
}

local xunyou = General(extension, "jy__xunyou", "wei", 3)
local qice = fk.CreateActiveSkill {
  name = "jy__qice",
  prompt = "#jy__qice-active",
  interaction = function()
    local handcards = Self:getCardIds(Player.Hand)
    local names, all_names = {}, {}
    for _, id in ipairs(Fk:getAllCardIds()) do
      local card = Fk:getCardById(id)
      if card:isCommonTrick() and not card.is_derived and not table.contains(all_names, card.name) then
        table.insert(all_names, card.name)
        local to_use = Fk:cloneCard(card.name)
        to_use:addSubcards(handcards)
        if Self:canUse(to_use) and not Self:prohibitUse(to_use) then
          local x = 0
          if to_use.multiple_targets and to_use.skill:getMinTargetNum() == 0 then
            for _, p in ipairs(Fk:currentRoom().alive_players) do
              if not Self:isProhibited(p, card) and card.skill:modTargetFilter(p.id, {}, Self, card, true) then
                x = x + 1
              end
            end
          end
          if x <= Self:getHandcardNum() then
            table.insert(names, card.name)
          end
        end
      end
    end
    if #names == 0 then return end
    return UI.ComboBox { choices = names, all_choices = all_names }
  end,
  card_num = 0,
  min_target_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isKongcheng()
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards, _, _, player)
    if self.interaction.data == nil then return false end
    local to_use = Fk:cloneCard(self.interaction.data)
    to_use.skillName = self.name
    to_use:addSubcards(player:getCardIds(Player.Hand))
    if not to_use.skill:targetFilter(to_select, selected, selected_cards, to_use, Util.DummyTable, player) then return false end
    if (#selected == 0 or to_use.multiple_targets) and
        player:isProhibited(Fk:currentRoom():getPlayerById(to_select), to_use) then
      return false
    end
    if to_use.multiple_targets then
      if #selected >= player:getHandcardNum() then return false end
      if to_use.skill:getMaxTargetNum(player, to_use) == 1 then
        local x = 0
        for _, p in ipairs(Fk:currentRoom().alive_players) do
          if p.id == to_select or (not Self:isProhibited(p, to_use) and to_use.skill:modTargetFilter(p.id, { to_select }, player, to_use, true)) then
            x = x + 1
          end
        end
        if x > player:getHandcardNum() then return false end
      end
    end
    return true
  end,
  feasible = function(self, selected, selected_cards, player)
    if self.interaction.data == nil then return false end
    local to_use = Fk:cloneCard(self.interaction.data)
    to_use.skillName = self.name
    to_use:addSubcards(Self:getCardIds(Player.Hand))
    return to_use.skill:feasible(selected, selected_cards, player, to_use)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcards(player:getCardIds(Player.Hand))
    card.skillName = self.name
    local use = {
      from = player.id,
      tos = table.map(effect.tos, function(id)
        return { id }
      end),
      card = card,
    }
    room:useCard(use)
    if not player.dead and player:getMark("@@jy__qice_transform") == 0 and room:askForChoice(player, { "transform_deputy", "Cancel" }, self.name) ~= "Cancel" then
      room:setPlayerMark(player, "@@jy__qice_transform", 1)
      H.transformGeneral(room, player)
    end
  end,
}
local zhiyu = fk.CreateTriggerSkill {
  name = "jy__zhiyu",
  anim_type = "masochism",
  events = { fk.Damaged },
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:drawCards(1, self.name)
    local cards = player:getCardIds("h")
    player:showCards(cards)
    if data.from and not data.from.dead and not data.from:isKongcheng() and
        table.every(cards, function(id) return #cards == 0 or Fk:getCardById(id).color == Fk:getCardById(cards[1]).color end) then
      room:askForDiscard(data.from, 1, 1, false, self.name, false)
    end
  end,
}
xunyou:addSkill(qice)
xunyou:addSkill(zhiyu)
xunyou:addCompanions("jy__xunyu")
Fk:loadTranslationTable {
  ["jy__xunyou"] = "荀攸",
  ["#jy__xunyou"] = "曹魏的谋主",

  ["jy__qice"] = "奇策",
  [":jy__qice"] = "出牌阶段限一次，你可将所有手牌当任意一张普通锦囊牌使用，你不能以此法使用目标数大于X的牌（X为你的手牌数），然后你可变更副将。",
  ["jy__zhiyu"] = "智愚",
  [":jy__zhiyu"] = "每当你受到一次伤害后，你可以摸一张牌，然后展示所有手牌，若颜色均相同，伤害来源弃置一张手牌。",

  ["#jy__qice-active"] = "发动 奇策，将所有手牌当一张锦囊牌使用",
  ["@@jy__qice_transform"] = "奇策 已变更",

  ["$jy__qice1"] = "倾力为国，算无遗策。",
  ["$jy__qice2"] = "奇策在此，谁与争锋？",
  ["$jy__zhiyu1"] = "大勇若怯，大智如愚。",
  ["$jy__zhiyu2"] = "愚者既出，智者何存？",
  ["~jy__xunyou"] = "主公，臣下……先行告退……",
}

local bianfuren = General(extension, "jy__bianfuren", "wei", 3, 3, General.Female)
local wanwei = fk.CreateTriggerSkill {
  name = "jy__wanwei",
  events = { fk.AfterCardsMove },
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryTurn) < 1 then
      for _, move in ipairs(data) do
        if move.from == player.id and (move.moveReason == fk.ReasonPrey or move.moveReason == fk.ReasonDiscard or move.moveReason == fk.ReasonGive) then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerEquip or info.fromArea == Card.PlayerHand then
              return true
            end
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,
}
local yuejian = fk.CreateMaxCardsSkill {
  name = "jy__yuejian",
  fixed_func = function(self, player)
    -- 只对拥有该技能的角色的“势力相同”角色生效
    local room = Fk:currentRoom()
    -- 检查场上是否有与player势力相同且拥有“jy__yuejian”技能的角色
    for _, p in ipairs(room.alive_players) do
      if p:hasSkill("jy__yuejian") and H.compareKingdomWith(player, p) then
        return player.maxHp
      end
    end
    -- 否则不改变手牌上限
  end
}
bianfuren:addCompanions("jy__caocao")
bianfuren:addSkill(wanwei)  ---待测试
bianfuren:addSkill(yuejian) ---待测试
Fk:loadTranslationTable {
  ["jy__bianfuren"] = "卞夫人",
  ["#jy__bianfuren"] = "奕世之雍容",

  ["jy__wanwei"] = "挽危",
  [":jy__wanwei"] = "当你的牌被弃置或获得时，你可以摸一张牌。",
  ["jy__yuejian"] = "约俭",
  [":jy__yuejian"] = "锁定技，与你势力相同角色的手牌上限改为其体力上限。",

  ["#jy__wanwei"] = "挽危：你可以摸一张牌",

  ["$jy__wanwei1"] = "梁、沛之间，非子廉无有今日。",
  ["$jy__wanwei2"] = "正使祸至，共死何苦！",
  ["$jy__yuejian1"] = "无文绣珠玉，器皆黑漆。",
  ["$jy__yuejian2"] = "性情约俭，不尚华丽。",
  ["~jy__bianfuren"] = "心肝涂地，惊愕断绝……",
}

local guohuai = General(extension, "jy__guohuai", "wei", 4)
local jy__jingce = fk.CreateTriggerSkill {
  name = "jy__jingce",
  anim_type = "drawcard",
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish and
        #player.room.logic:getEventsOfScope(GameEvent.UseCard, 998, function(e)
          local use = e.data[1]
          return use.from == player.id and not (use.card:isVirtual() and #use.card.subcards == 0) ---修复此处
        end, Player.HistoryTurn) > player.hp
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(2, self.name)
  end,
}
guohuai:addCompanions("jy__zhanghe")
guohuai:addSkill(jy__jingce)
Fk:loadTranslationTable {
  ["jy__guohuai"] = "郭淮",
  ["#jy__guohuai"] = "垂问秦雍",

  ["jy__jingce"] = "精策",
  [":jy__jingce"] = "结束阶段，若你本回合使用的实体牌数大于你的体力值，你可以摸两张牌。",

  ["$jy__jingce1"] = "方策精详，有备无患。",
  ["$jy__jingce2"] = "精兵据敌，策守如山。",
  ["~jy__guohuai"] = "姜维小儿，竟然……",
}

local cuiyanmaojie = General(extension, "jy__cuiyanmaojie", "wei", 3)
local zhengbi = fk.CreateTriggerSkill {
  name = "jy__zhengbi",
  anim_type = "control",
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play
        and (table.find(player:getCardIds(Player.Hand), function(id) return Fk:getCardById(id).type == Card.TypeBasic end)
          or table.every(player.room:getOtherPlayers(player, false), function(p) return H.getGeneralsRevealedNum(p) == 0 end))
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choices = {}
    local basic_cards1 = table.filter(player:getCardIds(Player.Hand), function(id)
      return Fk:getCardById(id).type == Card.TypeBasic
    end)
    local targets1 = table.map(table.filter(room:getOtherPlayers(player, false), function(p)
      return H.getGeneralsRevealedNum(p) > 0
    end), Util.IdMapper)
    local targets2 = table.map(table.filter(room:getOtherPlayers(player, false), function(p)
      return H.getGeneralsRevealedNum(p) == 0
    end), Util.IdMapper)
    if #basic_cards1 > 0 and #targets1 > 0 then
      table.insert(choices, "zhengbi_giveCard")
    end
    if #targets2 > 0 then
      table.insert(choices, "zhengbi_useCard")
    end
    if #choices == 0 then return false end
    local choice = room:askForChoice(player, choices, self.name)
    if choice:startsWith("zhengbi_giveCard") then
      local tos, id = room:askForChooseCardAndPlayers(player, targets1, 1, 1, ".|.|.|.|.|basic", "#jy__zhengbi-give",
        self.name, true)
      room:obtainCard(tos[1], id, false, fk.ReasonGive)
      local to = room:getPlayerById(tos[1])
      if to.dead or to:isNude() then return end
      local cards2 = to:getCardIds("he")
      if #cards2 > 1 then
        local card_choices = {}
        local num = #table.filter(to:getCardIds(Player.Hand), function(id)
          return Fk:getCardById(id).type == Card.TypeBasic
        end)
        if num > 1 then
          table.insert(card_choices, "zhengbi__basic-back:" .. player.id)
        end
        if #to:getCardIds("he") - num > 0 then
          table.insert(card_choices, "zhengbi__nobasic-back:" .. player.id)
        end
        if #card_choices == 0 then return false end
        local card_choice = room:askForChoice(to, card_choices, self.name)
        if card_choice:startsWith("zhengbi__basic-back") then
          cards2 = room:askForCard(to, 2, 2, false, self.name, false, ".|.|.|.|.|basic", "#jy__zhengbi-give1:" ..
            player.id)
        elseif card_choice:startsWith("zhengbi__nobasic-back") then
          cards2 = room:askForCard(to, 1, 1, true, self.name, false, ".|.|.|.|.|^basic", "#jy__zhengbi-give2:" ..
            player.id)
        end
      end
      room:moveCardTo(cards2, Player.Hand, player, fk.ReasonGive, self.name, nil, false, player.id)
    elseif choice:startsWith("zhengbi_useCard") then
      local to = room:askForChoosePlayers(player, targets2, 1, 1, "#jy__zhengbi_choose", self.name, true)
      if #to then
        room:setPlayerMark(room:getPlayerById(to[1]), "@@jy__zhengbi_choose-turn", 1)
      end
    end
  end,
  refresh_events = { fk.GeneralRevealed },
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(self) and target:getMark("@@jy__zhengbi_choose-turn") > 0
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:setPlayerMark(target, "@@jy__zhengbi_choose-turn", 0)
  end,
}
local zhengbi_targetmod = fk.CreateTargetModSkill {
  name = "#jy__zhengbi_targetmod",
  frequency = Skill.Compulsory,
  bypass_times = function(self, player, skill, scope, card, to)
    return card and player:hasSkill(zhengbi) and to:getMark("@@jy__zhengbi_choose-turn") > 0
  end,
  bypass_distances = function(self, player, skill, card, to)
    return card and player:hasSkill(zhengbi) and to:getMark("@@jy__zhengbi_choose-turn") > 0
  end,
}
local fengying = fk.CreateActiveSkill {
  name = "jy__fengying",
  anim_type = "support",
  frequency = Skill.Limited,
  card_num = 0,
  target_num = 0,
  card_filter = Util.FalseFunc,
  target_filter = Util.FalseFunc,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0 and not player:isKongcheng() and
        not player:prohibitUse(Fk:cloneCard("threaten_emperor"))
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:useVirtualCard("threaten_emperor", player:getCardIds(Player.Hand), player, player, self.name)
    local targets = table.map(table.filter(room.alive_players, function(p) return H.compareKingdomWith(p, player) end),
      Util.IdMapper)
    if #targets > 0 then
      for _, pid in ipairs(targets) do
        local p = room:getPlayerById(pid)
        if not p.dead then
          p:drawCards(math.max(0, p.maxHp - p:getHandcardNum()), self.name)
        end
      end
    end
  end,
}
zhengbi:addRelatedSkill(zhengbi_targetmod)
cuiyanmaojie:addSkill(zhengbi)
cuiyanmaojie:addSkill(fengying)
cuiyanmaojie:addCompanions("jy__caopi")
Fk:loadTranslationTable {
  ["jy__cuiyanmaojie"] = "崔琰毛玠",
  ["#jy__cuiyanmaojie"] = "日出月盛",

  ["jy__zhengbi"] = "征辟",
  [":jy__zhengbi"] = "出牌阶段开始时，你可选择一项：1.选择一名没有势力的角色，直至其确定势力或此回合结束，你对其使用牌无距离与次数限制；2.将一张基本牌交给一名已确定势力的角色，然后其交给你一张非基本牌或两张基本牌。",
  ["jy__fengying"] = "奉迎",
  [":jy__fengying"] = "限定技，出牌阶段，你可将所有手牌当【挟天子以令诸侯】（无视大势力限制）使用，然后所有与你势力相同的角色将手牌补至其体力上限。",

  ["zhengbi_giveCard"] = "交给有势力角色基本牌",
  ["zhengbi_useCard"] = "选择无势力角色用牌无限制",

  ["#jy__zhengbi-give"] = "请选择一张基本牌，交给一名有势力的角色",
  ["zhengbi__basic-back"] = "交给%src两张基本牌",
  ["zhengbi__nobasic-back"] = "交给%src一张非基本牌",

  ["#jy__zhengbi-give1"] = "征辟：请交给%src两张基本牌",
  ["#jy__zhengbi-give2"] = "征辟：请交给%src一张非基本牌",

  ["#jy__zhengbi_choose"] = "征辟：请选择一名未确定势力的角色，你对其使用牌无距离与次数限制",
  ["@@jy__zhengbi_choose-turn"] = "征辟",

  ["$jy__zhengbi1"] = "跅弛之士，在御之而已。",
  ["$jy__zhengbi2"] = "内不避亲，外不避仇。",
  ["$jy__fengying1"] = "二臣恭奉，以迎皇嗣。",
  ["$jy__fengying2"] = "奉旨典选，以迎忠良。",
  ["~jy__cuiyanmaojie"] = "为世所痛惜，冤哉……",
}

local jiangfei = General(extension, "jy__jiangwanfeiyi", "shu", 3)
local shengxi = fk.CreateTriggerSkill {
  name = "jy__shengxi",
  anim_type = "drawcard",
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    return player == target and player:hasSkill(self) and player.phase == Player.Finish and
        #player.room.logic:getActualDamageEvents(1, function(e) return e.data[1].from == player end) == 0
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(2, self.name)
  end,
}
local shoucheng = fk.CreateTriggerSkill {
  name = "jy__shoucheng",
  anim_type = "support",
  events = { fk.AfterCardsMove },
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return end
    for _, move in ipairs(data) do
      if move.from then
        local from = player.room:getPlayerById(move.from)
        if from:isKongcheng() and H.compareKingdomWith(from, player) and from.phase == Player.NotActive then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand then
              return true
            end
          end
        end
      end
    end
  end,
  on_trigger = function(self, event, target, player, data)
    local targets = {}
    local room = player.room
    for _, move in ipairs(data) do
      if move.from then
        local from = room:getPlayerById(move.from)
        if from:isKongcheng() and H.compareKingdomWith(from, player) and from.phase == Player.NotActive then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand then
              table.insertIfNeed(targets, from.id)
            end
          end
        end
      end
    end
    room:sortPlayersByAction(targets)
    for _, p in ipairs(targets) do
      local to = room:getPlayerById(p)
      if to.dead or not player:hasSkill(self) then break end
      self:doCost(event, to, player, nil)
    end
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#jy__shoucheng-draw::" .. target.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:doIndicate(player.id, { target.id })
    target:drawCards(1, self.name)
  end,
}
jiangfei:addSkill(shengxi)
jiangfei:addSkill(shoucheng)
jiangfei:addCompanions("jy__zhugeliang")
Fk:loadTranslationTable {
  ["jy__jiangwanfeiyi"] = "蒋琬费祎",
  ["#jy__jiangwanfeiyi"] = "社稷股肱",

  ["jy__shengxi"] = "生息",
  [":jy__shengxi"] = "结束阶段，若你于此回合内未造成过伤害，你可摸两张牌。",
  ["jy__shoucheng"] = "守成",
  [":jy__shoucheng"] = "与你势力相同的角色于其回合外失去手牌后，若其没有手牌，你可令其摸一张牌。",

  ["#jy__shoucheng-draw"] = "守成：你可令 %dest 摸一张牌",

  ["$jy__shengxi1"] = "国之生计，在民生息。",
  ["$jy__shengxi2"] = "安民止战，兴汉室！",
  ["$jy__shoucheng1"] = "待吾等助将军一臂之力！",
  ["$jy__shoucheng2"] = "国库盈余，可助军威。",
  ["~jy__jiangwanfeiyi"] = "墨守成规，终为其害啊……",
}

local jiangwei = General(extension, "jy__jiangwei", "shu", 4)
jiangwei:addCompanions("jy__zhugeliang")
jiangwei.deputyMaxHpAdjustedValue = -1
local tianfu = H.CreateArraySummonSkill {
  name = "jy__tianfu",
  array_type = "formation",
  relate_to_place = "m",
}
local tianfuTrig = fk.CreateTriggerSkill { -- FIXME
  name = '#jy__tianfu_trigger',
  visible = false,
  frequency = Skill.Compulsory,
  refresh_events = { fk.TurnStart, fk.GeneralRevealed, fk.EventAcquireSkill, "fk.RemoveStateChanged", fk.EventLoseSkill, fk.GeneralHidden },
  can_refresh = function(self, event, target, player, data)
    if event == fk.EventLoseSkill then
      return data == tianfu
    elseif event == fk.GeneralHidden then
      return player == target
    else
      return player:hasShownSkill(self.name, true, true)
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local ret = H.compareKingdomWith(room.current, player) and player:hasSkill(self) ---改了这里
    room:handleAddLoseSkills(player, ret and 'jy__kanpo' or "-jy__kanpo", nil, false, true)
  end,
}
tianfu:addRelatedSkill(tianfuTrig) ---待测试
local kanpo = fk.CreateViewAsSkill {
  name = "jy__kanpo",
  anim_type = "control",
  pattern = "nullification",
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).color == Card.Black and
        Fk:currentRoom():getCardArea(to_select) == Player.Hand
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return end
    local card = Fk:cloneCard("nullification")
    card.skillName = self.name
    card:addSubcard(cards[1])
    return card
  end,
}
local yizhi = fk.CreateTriggerSkill {
  name = "jy__yizhi",
  refresh_events = { fk.GeneralRevealed, fk.GeneralHidden, fk.EventLoseSkill },
  relate_to_place = "d",
  frequency = Skill.Compulsory,
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local has_head_guanxing = false
    for _, sname in ipairs(Fk.generals[player.general]:getSkillNameList()) do
      if Fk.skills[sname].trueName == "guanxing" then
        has_head_guanxing = true
        break
      end
    end
    local ret = player:hasShownSkill(self.name) and
    not (has_head_guanxing and player.general ~= "anjiang")                                                 --副将姜维，主将不是诸葛亮
    player.room:handleAddLoseSkills(player, ret and "jy__guanxing_jw" or "-jy__guanxing_jw", nil, false, true)
  end
}
local guanxing = fk.CreateTriggerSkill {
  name = "jy__guanxing_jw",
  anim_type = "control",
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
        player.phase == Player.Start
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:askForGuanxing(player, room:getNCards(math.min(5, #room.alive_players)))
  end,
}
local tiaoxin = fk.CreateActiveSkill {
  name = "jy__tiaoxin",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:currentRoom():getPlayerById(to_select):inMyAttackRange(Self)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local use = room:askForUseCard(target, "slash", "slash", "#jy__tiaoxin-use", true,
      { exclusive_targets = { player.id } })
    if use then
      room:useCard(use)
    else
      if not target:isNude() then
        local card = room:askForCardChosen(player, target, "he", self.name)
        room:throwCard({ card }, self.name, target, player)
      end
    end
  end
}
jiangwei:addSkill(tiaoxin)
jiangwei:addSkill(tianfu)
jiangwei:addRelatedSkill(kanpo)
jiangwei:addSkill(yizhi)
jiangwei:addRelatedSkill(guanxing)
Fk:loadTranslationTable {
  ["jy__jiangwei"] = "姜维",
  ["#jy__jiangwei"] = "龙的衣钵",
  ["designer:jy__jiangwei"] = "KayaK（淬毒）",
  ["illustrator:jy__jiangwei"] = "木美人",

  ["jy__tiaoxin"] = "挑衅",
  [":jy__tiaoxin"] = "出牌阶段限一次，你可令一名攻击范围内含有你的角色对你使用一张【杀】，否则你弃置其一张牌。",
  ["jy__tianfu"] = "天覆",
  [":jy__tianfu"] = "主将技，与你势力相同角色的回合内，你拥有〖看破〗。",
  ["jy__yizhi"] = "遗志",
  [":jy__yizhi"] = "副将技，此武将牌上单独的阴阳鱼个数-1；若你的主将的武将牌：有〖观星〗且处于明置状态，此〖观星〗改为固定观看五张牌；没有〖观星〗或处于暗置状态，你拥有〖观星〗。",

  ["jy__kanpo"] = "看破",
  [":jy__kanpo"] = "你可以将一张黑色手牌当【无懈可击】使用。",
  ["jy__guanxing_jw"] = "观星",
  [":jy__guanxing_jw"] = "准备阶段，你可将牌堆顶的X张牌（X为角色数且至多为5}）扣置入处理区（对你可见），你将其中任意数量的牌置于牌堆顶，将其余的牌置于牌堆底。",

  ["#jy__tiaoxin-use"] = "挑衅：对其使用一张【杀】，否则其弃置你一张牌",

  ["$jy__tiaoxin1"] = "小小娃娃，乳臭未干。",
  ["$jy__tiaoxin2"] = "快滚回去，叫你主将出来！",
  ["$jy__kanpo1"] = "丞相已教我识得此计。",
  ["$jy__kanpo2"] = "哼！有破绽！",
  ["$jy__guanxing_jw1"] = "天文地理，丞相所教，维铭记于心。",
  ["$jy__guanxing_jw2"] = "哪怕只有一线生机，我也不会放弃！",
  ["~jy__jiangwei"] = "臣等正欲死战，陛下何故先降？",
}

local jy__liufeng = General(extension, "jy__liufeng", "shu", 4)
local jy__xiansi = fk.CreateTriggerSkill {
  name = "jy__xiansi",
  anim_type = "control",
  attached_skill_name = "jy__xiansi&",
  derived_piles = "jy__liufeng_ni",
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and player.phase == Player.Start then
      return not table.every(player.room:getOtherPlayers(player), function(p) return p:isNude() end)
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room:getOtherPlayers(player), function(p)
      return not p:isNude()
    end), Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 1, 2, "#jy__xiansi-choose", self.name, true)
    if #tos > 0 then
      room:sortPlayersByAction(tos)
      self.cost_data = tos
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, pid in ipairs(self.cost_data) do
      if player.dead then break end
      local p = room:getPlayerById(pid)
      if not p:isNude() then
        local id = room:askForCardChosen(player, p, "he", self.name)
        player:addToPile("jy__liufeng_ni", id, true, self.name)
      end
    end
  end,
}
local jy__xiansi_viewas = fk.CreateViewAsSkill {
  name = "jy__xiansi&",
  anim_type = "negative",
  pattern = "slash",
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    local c = Fk:cloneCard("slash")
    c.skillName = "jy__xiansi"
    return c
  end,
  before_use = function(self, player, use)
    local room = player.room
    for _, id in ipairs(TargetGroup:getRealTargets(use.tos)) do
      local p = room:getPlayerById(id)
      if p:hasSkill("jy__xiansi", true) and #p:getPile("jy__liufeng_ni") > 1 then
        local cards = table.random(p:getPile("jy__liufeng_ni"), 2)
        room:moveCards({
          from = id,
          ids = cards,
          toArea = Card.DiscardPile,
          moveReason = fk.ReasonPutIntoDiscardPile,
          skillName = "jy__xiansi",
        })
        break
      end
    end
  end,
  enabled_at_play = function(self, player)
    return table.find(Fk:currentRoom().alive_players, function(p)
      return (p:hasSkill("jy__xiansi", true) and #p:getPile("jy__liufeng_ni") > 1)
    end)
  end,
  enabled_at_response = function(self, player, response)
    return not response and table.find(Fk:currentRoom().alive_players, function(p)
      return (p:hasSkill("jy__xiansi", true) and #p:getPile("jy__liufeng_ni") > 1)
    end)
  end,
}
local jy__xiansi_prohibit = fk.CreateProhibitSkill { --FIXME: 目标多指！
  name = "#jy__xiansi_prohibit",
  is_prohibited = function(self, from, to, card)
    if from:hasSkill(self, true) then
      return card.trueName == "slash" and table.contains(card.skillNames, "jy__xiansi") and
          not (to:hasSkill("jy__xiansi", true) and #to:getPile("jy__liufeng_ni") > 1)
    end
  end,
}
jy__xiansi_viewas:addRelatedSkill(jy__xiansi_prohibit)
Fk:addSkill(jy__xiansi_viewas)
jy__liufeng:addSkill(jy__xiansi)
Fk:loadTranslationTable {
  ["jy__liufeng"] = "刘封",
  ["#jy__liufeng"] = "骑虎之殇",
  ["designer:jy__liufeng"] = "香蒲神殇",
  ["illustrator:jy__liufeng"] = "Thinking",
  ["jy__xiansi"] = "陷嗣",
  [":jy__xiansi"] = "回合开始阶段开始时，你可以将至多两名其他角色的各一张牌置于你的武将牌上，称为“逆”。每当其他角色需要对你使用一张【杀】时，" ..
      "该角色可以弃置你武将牌上的两张“逆”，视为对你使用一张【杀】。",
  ["#jy__xiansi-choose"] = "陷嗣：你可以将至多两名其他角色各一张牌置为“逆”",
  ["jy__liufeng_ni"] = "逆",
  ["jy__xiansi&"] = "陷嗣",
  [":jy__xiansi&"] = "当你需使用【杀】时，你可以弃置刘封的两张“逆”，视为对其使用一张【杀】。",

  ["$jy__xiansi1"] = "袭人于不意，溃敌于无形！",
  ["$jy__xiansi2"] = "破敌军阵，父亲定会刮目相看！",
  ["$jy__xiansi3"] = "此乃孟达之计，非我所愿！",
  ["$jy__xiansi4"] = "我有何罪？！",
  ["~jy__liufeng"] = "父亲，为什么……",
}

local jy__mifuren = General(extension, "jy__mifuren", "shu", 3, 3, General.Female)
local jy__guixiu = fk.CreateTriggerSkill {
  name = "jy__guixiu",
  anim_type = "drawcard",
  events = { fk.GeneralRevealed, "fk.GeneralRemoved" },
  can_trigger = function(self, event, target, player, data)
    if target ~= player then return false end
    if event == "fk.GeneralRemoved" then
      return player:isWounded() and table.contains(Fk.generals[data]:getSkillNameList(), self.name)
    else
      if player:hasSkill(self) then
        for _, v in pairs(data) do
          if table.contains(Fk.generals[v]:getSkillNameList(), self.name) then return true end
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil,
      "#jy__guixiu-" .. (event == fk.GeneralRevealed and "draw" or "recover"))
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.GeneralRevealed then
      player:drawCards(2, self.name)
    else
      player.room:recover {
        who = player,
        num = 1,
        skillName = self.name,
      }
    end
  end
}
local jy__cunsi = fk.CreateActiveSkill {
  name = "jy__cunsi",
  anim_type = "big",
  target_num = 1,
  target_filter = function(self, to_select, selected)
    return #selected == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local isDeputy = H.inGeneralSkills(player, self.name)
    if isDeputy then
      H.removeGeneral(room, player, isDeputy == "d")
    end
    local target = room:getPlayerById(effect.tos[1])
    room:handleAddLoseSkills(target, "jy__yongjue", nil)
    if target ~= player and not target.dead then
      target:drawCards(2, self.name)
    end
  end,
}
local jy__yongjue = fk.CreateTriggerSkill {
  name = "jy__yongjue",
  anim_type = "support",
  events = { fk.CardUseFinished },
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and H.compareKingdomWith(target, player) and not target.dead and data.card.trueName == "slash" and target.phase == Player.Play then
      local events = target.room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
        local use = e.data[1]
        return use.from == target.id
      end, Player.HistoryPhase)
      if #events == 1 and events[1].id == target.room.logic:getCurrentEvent().id then
        local cards = Card:getIdList(data.card)
        return #cards > 0 and table.every(cards, function(id) return target.room:getCardArea(id) == Card.Processing end)
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    return target.room:askForSkillInvoke(target, self.name, nil, "#jy__yongjue-invoke:::" .. data.card:toLogString())
  end,
  on_use = function(self, event, target, player, data)
    local room = target.room
    -- room:doIndicate(player.id, {target.id})
    room:obtainCard(target, data.card, true, fk.ReasonJustMove)
  end,
}
jy__mifuren:addSkill(jy__guixiu)
jy__mifuren:addSkill(jy__cunsi)
jy__mifuren:addRelatedSkill(jy__yongjue)
Fk:loadTranslationTable {
  ['jy__mifuren'] = '糜夫人',
  ["#jy__mifuren"] = "乱世沉香",
  ["designer:jy__mifuren"] = "淬毒",
  ["illustrator:jy__mifuren"] = "木美人",

  ["jy__guixiu"] = "闺秀",
  [":jy__guixiu"] = "当你：1.明置此武将牌后，你可摸两张牌：2.移除此武将牌后，你回复1点体力。",
  ["jy__cunsi"] = "存嗣",
  [":jy__cunsi"] = "出牌阶段，你可移除此武将牌并选择一名角色，其获得〖勇决〗。若其不为你，其摸两张牌。", -- canShowInPlay 若此武将牌处于明置状态
  ["jy__yongjue"] = "勇决",
  [":jy__yongjue"] = "当与你势力相同的角色于其出牌阶段内使用【杀】结算后，若此【杀】为其于此阶段内使用的第一张牌，其可获得此【杀】对应的所有实体牌。",

  ["#jy__guixiu-draw"] = "是否发动“闺秀”，摸两张牌",
  ["#jy__guixiu-recover"] = "是否发动“闺秀”，回复1点体力",
  ["#jy__yongjue-invoke"] = "勇决：你可以获得此%arg",

  ["$jy__guixiu1"] = "闺中女子，亦可秀气英拔。",
  ["$jy__guixiu2"] = "闺楼独看花月，倚窗顾影自怜。",
  ["$jy__cunsi1"] = "存汉室之嗣，留汉室之本。",
  ["$jy__cunsi2"] = "一切，便托付将军了……",
  ["$jy__yongjue1"] = "能救一个是一个！",
  ["$jy__yongjue2"] = "扶幼主，成霸业！",
  ["~jy__mifuren"] = "阿斗被救，妾身再无牵挂…",
}

local jy__shamoke = General(extension, "jy__shamoke", "shu", 4)
local jy__jilis = fk.CreateTriggerSkill {
  name = "jy__jilis",
  anim_type = "drawcard",
  events = { fk.CardUsing, fk.CardResponding },
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      local x, y = player:getAttackRange(), player:getMark("jy__jilis_times-turn")
      if x >= y then
        local room = player.room
        local logic = room.logic
        local end_id = player:getMark("jy__jilis_record-turn")
        local e = logic:getCurrentEvent()
        if end_id == 0 then
          local turn_event = e:findParent(GameEvent.Turn, false)
          if turn_event == nil then return false end
          end_id = turn_event.id
        end
        room:setPlayerMark(player, "jy__jilis_record-turn", logic.current_event_id)
        local events = logic.event_recorder[GameEvent.UseCard] or Util.DummyTable
        for i = #events, 1, -1 do
          e = events[i]
          if e.id <= end_id then break end
          local use = e.data[1]
          if use.from == player.id then
            y = y + 1
          end
        end
        events = logic.event_recorder[GameEvent.RespondCard] or Util.DummyTable
        for i = #events, 1, -1 do
          e = events[i]
          if e.id <= end_id then break end
          local use = e.data[1]
          if use.from == player.id then
            y = y + 1
          end
        end
        room:setPlayerMark(player, "jy__jilis_times-turn", y)
        return x == y
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(player:getAttackRange())
  end,
}
jy__shamoke:addSkill(jy__jilis)
Fk:loadTranslationTable {
  ['jy__shamoke'] = '沙摩柯',
  ["#jy__shamoke"] = "五溪蛮王",

  ["jy__jilis"] = "蒺藜",
  [":jy__jilis"] = "当你于一回合内使用或打出第X张牌时，你可以摸X张牌（X为你的攻击范围）。",

  ["$jy__jilis1"] = "蒺藜骨朵，威震慑敌！",
  ["$jy__jilis2"] = "看我一招，铁蒺藜骨朵！",
  ['~jy__shamoke'] = '五溪蛮夷，不可能输！',
}

local masu = General(extension, "jy__masu", "shu", 3)
local sanyao = fk.CreateActiveSkill {
  name = "jy__sanyao",
  anim_type = "offensive",
  card_num = 1,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isNude()
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and not Self:prohibitDiscard(Fk:getCardById(to_select))
  end,
  target_filter = function(self, to_select, selected)
    local target = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and (target:getHandcardNum() > Self:getHandcardNum() or target.hp > Self.hp)
  end,
  -- on_use = function(self, room, effect)
  --   local player = room:getPlayerById(effect.from)
  --   room:throwCard(effect.cards, self.name, player, player)
  --   local targets = table.map(table.filter(room:getOtherPlayers(player), function(p)
  --     return
  --         p ~= player and (p:getHandcardNum() > player:getHandcardNum() or p.hp > player.hp)
  --   end), Util.IdMapper)
  --   if #targets == 0 then return false end
  --   local target = room:askForChoosePlayers(player, targets, 1, 1, "#jy__sanyao-choose", self.name, false)
  --   room:damage {
  --     from = player,
  --     to = room:getPlayerById(target[1]),
  --     damage = 1,
  --     skillName = self.name,
  --   }
  -- end
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:throwCard(effect.cards, self.name, player, player)
    room:damage {
      from = player,
      to = target,
      damage = 1,
      skillName = self.name,
    }
  end
}
local zhiman = fk.CreateTriggerSkill {
  name = "jy__zhiman",
  events = { fk.DamageCaused },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.to ~= player
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#jy__zhiman-invoke::" .. data.to.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local target = data.to
    if #target:getCardIds { Player.Equip, Player.Judge } > 0 then -- 开摆！
      local card = room:askForCardChosen(player, target, "ej", self.name)
      room:obtainCard(player, card, true, fk.ReasonPrey)
    end
    if H.compareKingdomWith(target, player) and player:getMark("@@jy__zhiman_transform") == 0
        and room:askForChoice(player, { "jy__zhiman_transform::" .. target.id, "Cancel" }, self.name) ~= "Cancel"
        and room:askForChoice(target, { "transform_deputy", "Cancel" }, self.name) ~= "Cancel" then
      room:setPlayerMark(player, "@@jy__zhiman_transform", 1)
      H.transformGeneral(room, target)
    end
    return true
  end
}
masu:addSkill(sanyao)
masu:addSkill(zhiman)
Fk:loadTranslationTable {
  ['jy__masu'] = '马谡',
  ["#jy__masu"] = "帷幄经谋",
  ["designer:jy__masu"] = "点点",
  ["illustrator:jy__masu"] = "蚂蚁君",

  ["jy__sanyao"] = "散谣",
  [":jy__sanyao"] = "出牌阶段限一次，你可以选择一名手牌数或体力值大于你的角色，然后弃置一张牌，令你对其造成1点伤害。",
  ["jy__zhiman"] = "制蛮",
  [":jy__zhiman"] = "当你对其他角色造成伤害时，你可防止此伤害，你获得其装备区或判定区里的一张牌。若其与你势力相同，你可令其选择是否变更。",
  ["#jy__zhiman-invoke"] = "制蛮：你可以防止对 %dest 造成的伤害，获得其场上的一张牌。若其与你势力相同，你可令其选择是否变更副将",
  ["jy__zhiman_transform"] = "令%dest选择是否变更副将",
  ["@@jy__zhiman_transform"] = "制蛮 已变更",

  ["$jy__sanyao1"] = "三人成虎，事多有。",
  ["$jy__sanyao2"] = "散谣惑敌，不攻自破！",
  ["$jy__zhiman1"] = "兵法谙熟于心，取胜千里之外！",
  ["$jy__zhiman2"] = "丞相多虑，且看我的！",
  ["~jy__masu"] = "败军之罪，万死难赎……",
}

local fazheng = General(extension, "jy__fazheng", "shu", 3)
fazheng:addCompanions("jy__liubei")
local enyuan = fk.CreateTriggerSkill {
  name = "jy__enyuan",
  events = { fk.TargetConfirmed, fk.Damaged },
  frequency = Skill.Compulsory,
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if target ~= player or not player:hasSkill(self) then return false end
    if event == fk.Damaged then
      return data.from and not data.from.dead
    else
      return data.card.trueName == "peach" and data.from ~= player.id and not player.room:getPlayerById(data.from).dead
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetConfirmed then
      room:notifySkillInvoked(player, self.name, "support")
      player:broadcastSkillInvoke(self.name, 2)
      local from = data.from
      if from and not room:getPlayerById(from).dead then
        room:doIndicate(player.id, { from })
        room:getPlayerById(from):drawCards(1, self.name)
      end
    else
      room:notifySkillInvoked(player, self.name, "masochism")
      player:broadcastSkillInvoke(self.name, 1)
      local from = data.from
      if from and not from.dead then
        room:doIndicate(player.id, { from.id })
        if from == player then
          room:loseHp(player, 1, self.name)
        else
          local card = room:askForCard(from, 1, 1, false, self.name, true, ".|.|.|hand", "#jy__enyuan-give:" .. player
            .id)
          if #card > 0 then
            room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonGive, self.name, nil, false, player.id)
          else
            room:loseHp(from, 1, self.name)
          end
        end
      end
    end
  end,
}
local wushengXH = fk.CreateViewAsSkill {
  name = "xuanhuo__jy__wusheng",
  anim_type = "offensive",
  pattern = "slash",
  card_filter = function(self, to_select, selected)
    if #selected == 1 then return false end
    return (H.getHegLord(Fk:currentRoom(), Self) and H.getHegLord(Fk:currentRoom(), Self):hasSkill("shouyue")) or
        Fk:getCardById(to_select).color == Card.Red
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then
      return nil
    end
    local c = Fk:cloneCard("slash")
    c.skillName = self.name
    c:addSubcard(cards[1])
    return c
  end,
}
local wusheng_targetmod = fk.CreateTargetModSkill {
  name = "#xuanhuo__jy__wusheng_targetmod",
  anim_type = "offensive",
  bypass_distances = function(self, player, skill, card, to)
    return player:hasSkill(wushengXH) and skill.trueName == "slash_skill" and card.suit == Card.Diamond
  end
}
wushengXH:addRelatedSkill(wusheng_targetmod)
local paoxiaoTriggerXH = fk.CreateTriggerSkill {
  name = "#xuanhuo__jy__paoxiaoTrigger",
  events = { fk.CardUsing },
  anim_type = "offensive",
  visible = false,
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if target ~= player or not player:hasSkill(self) or data.card.trueName ~= "slash" then return false end
    local events = player.room.logic:getEventsOfScope(GameEvent.UseCard, 2, function(e)
      local use = e.data[1]
      return use.from == player.id and use.card.trueName == "slash"
    end, Player.HistoryTurn)
    return #events == 2 and events[2].id == player.room.logic:getCurrentEvent().id
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,

  refresh_events = { fk.CardUsing, fk.TargetSpecified, fk.CardUseFinished },
  can_refresh = function(self, event, target, player, data)
    if player ~= target then return false end -- 摆一下
    if event == fk.CardUsing then
      return player:hasSkill(self) and data.card.trueName == "slash" and player:usedCardTimes("slash") > 1
    else
      local room = player.room
      if not H.getHegLord(room, player) or not H.getHegLord(room, player):hasSkill("shouyue") then return false end
      if event == fk.CardUseFinished then
        return (data.extra_data or {}).xhHsPaoxiaoNullifiled
      else
        return data.card.trueName == "slash" and player:hasSkill("xuanhuo__jy__paoxiao") and
            room:getPlayerById(data.to):isAlive()
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUsing then
      player:broadcastSkillInvoke("jy__paoxiao")
      room:doAnimate("InvokeSkill", {
        name = "paoxiao",
        player = player.id,
        skill_type = "offensive",
      })
    elseif event == fk.CardUseFinished then
      for key, num in pairs(data.extra_data.xhHsPaoxiaoNullifiled) do
        local p = room:getPlayerById(tonumber(key))
        if p:getMark(fk.MarkArmorNullified) > 0 then
          room:removePlayerMark(p, fk.MarkArmorNullified, num)
        end
      end
      data.xhHsPaoxiaoNullifiled = nil
    else
      room:addPlayerMark(room:getPlayerById(data.to), fk.MarkArmorNullified)
      data.extra_data = data.extra_data or {}
      data.extra_data.xhHsPaoxiaoNullifiled = data.extra_data.xhHsPaoxiaoNullifiled or {}
      data.extra_data.xhHsPaoxiaoNullifiled[tostring(data.to)] = (data.extra_data.xhHsPaoxiaoNullifiled[tostring(data.to)] or 0) +
          1
    end
  end,
}
local paoxiaoXH = fk.CreateTargetModSkill {
  name = "xuanhuo__jy__paoxiao",
  frequency = Skill.Compulsory,
  bypass_times = function(self, player, skill, scope)
    if player:hasSkill(self) and skill.trueName == "slash_skill"
        and scope == Player.HistoryPhase then
      return true
    end
  end,
}
paoxiaoXH:addRelatedSkill(paoxiaoTriggerXH)
local longdanXH = fk.CreateViewAsSkill {
  name = "xuanhuo__jy__longdan",
  pattern = "slash,jink",
  card_filter = function(self, to_select, selected)
    if #selected == 1 then return false end
    local _c = Fk:getCardById(to_select)
    local c
    if _c.trueName == "slash" then
      c = Fk:cloneCard("jink")
    elseif _c.name == "jink" then
      c = Fk:cloneCard("slash")
    else
      return false
    end
    return (Fk.currentResponsePattern == nil and Self:canUse(c)) or
        (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(c))
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then
      return nil
    end
    local _c = Fk:getCardById(cards[1])
    local c
    if _c.trueName == "slash" then
      c = Fk:cloneCard("jink")
    elseif _c.name == "jink" then
      c = Fk:cloneCard("slash")
    end
    c.skillName = self.name
    c:addSubcard(cards[1])
    return c
  end,
}
local longdanAfterXH = fk.CreateTriggerSkill {
  name = "#xuanhuo__longdan_after",
  anim_type = "offensive",
  visible = false,
  events = { fk.CardEffectCancelledOut, fk.CardUsing, fk.CardResponding },
  can_trigger = function(self, event, target, player, data)
    if event == fk.CardEffectCancelledOut then
      if data.card.trueName ~= "slash" then return false end
      if target == player then         -- 龙胆杀
        return table.contains(data.card.skillNames, "xuanhuo__jy__longdan")
      elseif data.to == player.id then -- 龙胆闪
        for _, card in ipairs(data.cardsResponded) do
          if card.name == "jink" and table.contains(card.skillNames, "xuanhuo__jy__longdan") then
            return true
          end
        end
      end
    else
      local room = player.room
      return player == target and H.getHegLord(room, player) and
          table.contains(data.card.skillNames, "xuanhuo__jy__longdan") and H.getHegLord(room, player):hasSkill("shouyue")
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardEffectCancelledOut then
      if target == player then
        local targets = table.map(room:getOtherPlayers(room:getPlayerById(data.to)), Util.IdMapper)
        if #targets == 0 then return false end
        local target = room:askForChoosePlayers(player, targets, 1, 1, "#longdan_slash-ask::" .. data.to, self.name, true)
        if #target > 0 then
          self.cost_data = target[1]
          return true
        end
        return false
      else
        local targets = table.map(table.filter(room:getOtherPlayers(target), function(p)
          return
              p ~= player and p:isWounded()
        end), Util.IdMapper)
        if #targets == 0 then return false end
        local target = room:askForChoosePlayers(player, targets, 1, 1, "#longdan_jink-ask::" .. target.id, self.name,
          true)
        if #target > 0 then
          self.cost_data = target[1]
          return true
        end
      end
    else
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    if event == fk.CardEffectCancelledOut then
      if target == player then
        room:damage {
          from = player,
          to = to,
          damage = 1,
          skillName = self.name,
        }
      else
        room:recover({
          who = to,
          num = 1,
          recoverBy = player,
          skillName = self.name,
        })
      end
    else
      player:drawCards(1, self.name)
    end
  end,
}
local tieqiXH = fk.CreateTriggerSkill {
  name = "xuanhuo__jy__tieqi",
  anim_type = "offensive",
  events = { fk.TargetSpecified },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.trueName == "slash"
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(data.to)
    local judge = {
      who = player,
      reason = self.name,
      pattern = ".|.|spade,club,heart,diamond",
    }
    if player.dead then return end
    local choices = {}
    if to.general ~= "anjiang" then
      table.insert(choices, to.general)
    end
    if to.deputyGeneral ~= "anjiang" then
      table.insert(choices, to.deputyGeneral)
    end
    if #choices > 0 then
      local choice
      if H.getHegLord(room, player) and #choices > 1 and H.getHegLord(room, player):hasSkill("shouyue") then
        choice = choices
      else
        choice = { room:askForChoice(player, choices, self.name, "#jy__tieqi-ask::" .. to.id) }
      end
      local record = to:getTableMark("@jy__tieqi-turn")
      for _, c in ipairs(choice) do
        table.insertIfNeed(record, c)
        room:setPlayerMark(to, "@jy__tieqi-turn", record)
        local mark = to:getTableMark("_jy__tieqi-turn")
        for _, skill_name in ipairs(Fk.generals[c]:getSkillNameList()) do
          if Fk.skills[skill_name].frequency ~= Skill.Compulsory then
            table.insertIfNeed(mark, skill_name)
          end
        end
        room:setPlayerMark(to, "_jy__tieqi-turn", mark)
      end
    end
    room:judge(judge)
    if judge.card.suit ~= nil then
      local suits = {}
      table.insert(suits, judge.card:getSuitString())
      if #room:askForDiscard(to, 1, 1, false, self.name, true, ".|.|" .. table.concat(suits, ","), "#jy__tieqi-discard:::" .. judge.card:getSuitString()) == 0 then
        data.disresponsive = true
      end
    end
  end,
}
local tieqiInvalidityXH = fk.CreateInvaliditySkill {
  name = "#xuanhuo__jy__tieqi_invalidity",
  invalidity_func = function(self, from, skill)
    if from:getMark("_jy__tieqi-turn") ~= 0 then
      return table.contains(from:getMark("_jy__tieqi-turn"), skill.name) and
          (skill.frequency ~= Skill.Compulsory and skill.frequency ~= Skill.Wake) and not skill.name:endsWith("&")
    end
  end
}
tieqiXH:addRelatedSkill(tieqiInvalidityXH)
local liegongXH = fk.CreateTriggerSkill {
  name = "jy__liegongXH",
  anim_type = "offensive",
  events = { fk.TargetSpecified },
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
        data.card.trueName == "slash"
  end,
  on_use = function(self, event, target, player, data)
    data.disresponsive = true
  end,
}
local liegongXH_mod = fk.CreateTargetModSkill {
  name = "#jy__liegongXH_mod",
  bypass_distances = function(self, player, skill, card)
    return player:hasSkill(self) and card and card.trueName == "slash"
  end,
}
liegongXH:addRelatedSkill(liegongXH_mod)
local kuangguXH = fk.CreateTriggerSkill {
  name = "xuanhuo__jy__kuanggu",
  anim_type = "drawcard",
  events = { fk.Damage },
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and (data.extra_data or {}).kuanggucheck
  end,
  on_trigger = function(self, event, target, player, data)
    self.cancel_cost = false
    for i = 1, data.damage do
      self:doCost(event, target, player, data)
      if self.cost_data == "Cancel" then break end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local choices = { "draw1", "Cancel" }
    if player:isWounded() then
      table.insert(choices, 2, "recover")
    end
    self.cost_data = room:askForChoice(player, choices, self.name)
    return self.cost_data ~= "Cancel"
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if self.cost_data == "recover" then
      room:recover({
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name
      })
    elseif self.cost_data == "draw1" then
      player:drawCards(1, self.name)
    end
  end,

  refresh_events = { fk.BeforeHpChanged },
  can_refresh = function(self, event, target, player, data)
    return data.damageEvent and player == data.damageEvent.from and player:compareDistance(target, 2, "<")
  end,
  on_refresh = function(self, event, target, player, data)
    data.damageEvent.extra_data = data.damageEvent.extra_data or {}
    data.damageEvent.extra_data.kuanggucheck = true
  end,
}
local xuanhuo = fk.CreateTriggerSkill {
  name = "jy__xuanhuo",
  mute = true,
  attached_skill_name = "jy__xuanhuo_other&",
  refresh_events = { fk.AfterPropertyChange, fk.GeneralRevealed, fk.GeneralHidden, fk.Deathed },
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local players = room.alive_players
    local fazhengs = table.filter(players, function(p) return p:hasShownSkill(self) end)
    local xuanhuo_map = {}
    for _, p in ipairs(players) do
      local will_attach = false
      for _, fazheng in ipairs(fazhengs) do
        if (fazheng ~= p and H.compareKingdomWith(fazheng, p)) then
          will_attach = true
          break
        end
      end
      xuanhuo_map[p] = will_attach
    end
    for p, v in pairs(xuanhuo_map) do
      if v ~= p:hasSkill("jy__xuanhuo_other&") then
        room:handleAddLoseSkills(p, v and self.attached_skill_name or "-" .. self.attached_skill_name, nil, false, true)
      end
    end
  end,

  on_acquire = function(self, player)
    local room = player.room
    for _, p in ipairs(room.alive_players) do
      if p ~= player and H.compareKingdomWith(player, p) then
        room:handleAddLoseSkills(p, self.attached_skill_name, nil, false, true)
      end
    end
  end,
  on_lose = function(self, player, is_death)
    local room = player.room
    for _, p in ipairs(room.alive_players) do
      if p ~= player and H.compareKingdomWith(player, p) then
        room:handleAddLoseSkills(p, "-" .. self.attached_skill_name, nil, false, true)
      end
    end
  end,
}
local xuanhuoOther = fk.CreateActiveSkill {
  name = "jy__xuanhuo_other&",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and
        table.find(Fk:currentRoom().alive_players, function(p)
          return p:hasSkill(xuanhuo) and H.compareKingdomWith(p, player) and p ~= Self
        end)
  end,
  card_num = 1,
  card_filter = function(self, to_select, selected)
    return #selected < 1 and Fk:currentRoom():getCardArea(to_select) == Player.Hand
  end,
  target_num = 0,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local targets = table.filter(room:getOtherPlayers(player, false),
      function(p) return p:hasShownSkill(xuanhuo) and H.compareKingdomWith(p, player) end)
    if #targets == 0 then return false end
    local to
    if #targets == 1 then
      to = targets[1]
    else
      to = room:getPlayerById(room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, nil, self.name,
        false)[1])
    end
    room:doIndicate(player.id, { to.id })
    to:broadcastSkillInvoke(self.name)
    room:moveCardTo(effect.cards, Player.Hand, to, fk.ReasonGive, self.name, nil, false, to.id)
    if player:isNude() or not room:askForDiscard(player, 1, 1, true, self.name, false, nil, "#jy__xuanhuo-ask") then return false end
    if player.dead then return false end
    local all_choices = { "xuanhuo__jy__wusheng", "xuanhuo__jy__paoxiao", "xuanhuo__jy__longdan", "xuanhuo__jy__tieqi",
      "xuanhuo__jy__liegong", "xuanhuo__jy__kuanggu" }
    -- {"jy__wusheng", "jy__paoxiao", "jy__longdan","jy__tieqi", "jy__liegongXH", "jy__kuanggu"}
    local choices = {}
    local skills = {}
    for _, p in ipairs(room.alive_players) do
      for _, s in ipairs(p.player_skills) do
        table.insert(skills, s.name)
      end
    end
    for _, skill in ipairs(all_choices) do
      local skillNames = { skill, skill:sub(10) }
      local can_choose = true
      for _, sname in ipairs(skills) do
        if table.contains(skillNames, sname) then
          can_choose = false
          break
        end
      end
      if can_choose then table.insert(choices, skill) end
    end
    if #choices == 0 then return false end

    local choice = room:askForChoice(player, choices, self.name, "#jy__xuanhuo-choice", true, all_choices)
    room:handleAddLoseSkills(player, choice, nil)
    room:addTableMark(player, "@jy__xuanhuo_skills-turn", choice)
  end,
}
local xuanhuoOtherLose = fk.CreateTriggerSkill {
  name = "#jy__xuanhuo_other_lose&",
  visible = false,
  refresh_events = { fk.EventPhaseStart, fk.GeneralRevealed },
  can_refresh = function(self, event, target, player, data)
    if type(player:getMark("@jy__xuanhuo_skills-turn")) ~= "table" then return false end
    if event == fk.EventPhaseStart then
      return target == player and player.phase == Player.NotActive
    else
      return true
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      local _skills = player:getMark("@jy__xuanhuo_skills-turn")
      local skills = "-" .. table.concat(_skills, "|-")
      room:handleAddLoseSkills(player, skills, nil, false, true)
      room:setPlayerMark(player, "@jy__xuanhuo_skills-turn", 0)
    else
      local skills = {}
      table.forEach(room.alive_players, function(p) table.insertTable(skills, p.player_skills) end)
      local xuanhuoSkills = player:getMark("@jy__xuanhuo_skills-turn")
      if type(xuanhuoSkills) == "table" then
        local detachList = {}
        for _, skill in ipairs(skills) do
          local skillName = "xuanhuo__" .. skill.name
          if (table.contains(xuanhuoSkills, skillName)) then
            table.removeOne(xuanhuoSkills, skillName)
            table.insert("-" .. skillName)
          end
        end
        if #detachList > 0 then
          room:handleAddLoseSkills(player, table.concat(detachList, "|"), nil)
          room:setPlayerMark(player, "@jy__xuanhuo_skills-turn", #xuanhuoSkills > 0 and xuanhuoSkills or 0)
        end
      end
    end
  end,
}
xuanhuoOther:addRelatedSkill(xuanhuoOtherLose)
Fk:addSkill(xuanhuoOther)

fazheng:addSkill(enyuan)
fazheng:addSkill(xuanhuo)
fazheng:addRelatedSkill(wushengXH)
fazheng:addRelatedSkill(paoxiaoXH)
fazheng:addRelatedSkill(longdanXH)
fazheng:addRelatedSkill(tieqiXH)
fazheng:addRelatedSkill(liegongXH)
fazheng:addRelatedSkill(kuangguXH)

Fk:loadTranslationTable {
  ["jy__fazheng"] = "法正",
  ["#jy__fazheng"] = "蜀汉的辅翼",
  ["illustrator:jy__fazheng"] = "黑白画谱",

  ["jy__enyuan"] = "恩怨",
  [":jy__enyuan"] = "锁定技，当你成为【桃】的目标后，若使用者不为你，其摸一张牌；当你受到伤害后，伤害来源需交给你一张手牌，否则失去1点体力。",
  ["jy__xuanhuo"] = "眩惑",
  [":jy__xuanhuo"] = "与你势力相同的其他角色的出牌阶段限一次，其可交给你一张手牌，然后其弃置一张牌，选择下列技能中的一个：〖武圣〗〖咆哮〗〖龙胆〗〖铁骑〗〖烈弓〗〖狂骨〗（场上已有的技能无法选择）。其于此回合内或明置有其以此法选择的技能的武将牌之前拥有其以此法选择的技能。",

  ["jy__xuanhuo_other&"] = "眩惑",
  [":jy__xuanhuo_other&"] = "你可交给法正一张手牌，然后弃置一张牌，选择下列技能中的一个：〖武圣〗〖咆哮〗〖龙胆〗〖铁骑〗〖烈弓〗〖狂骨〗（场上已有的技能无法选择）。你于此回合内或明置有以此法选择的技能的武将牌之前拥有以此法选择的技能。",
  ["xuanhuo__jy__wusheng"] = "武圣",
  ["xuanhuo__jy__paoxiao"] = "咆哮",
  ["xuanhuo__jy__longdan"] = "龙胆",
  ["xuanhuo__jy__tieqi"] = "铁骑",
  ["xuanhuo__jy__liegong"] = "烈弓",
  ["xuanhuo__jy__kuanggu"] = "狂骨",
  [":xuanhuo__jy__wusheng"] = "你可将一张红色牌当【杀】使用或打出。你使用的方块【杀】无距离限制。",
  [":xuanhuo__jy__paoxiao"] = "锁定技，你使用【杀】无次数限制。当你于一个回合内使用第二张【杀】时，你摸一张牌。",
  [":xuanhuo__jy__longdan"] = "你可将【闪】当【杀】使用或打出，当此【杀】被一名角色使用的【闪】抵消后，你可对另一名角色造成1点伤害。你可将【杀】当【闪】使用或打出，当一名角色使用的【杀】被此【闪】抵消后，你可令另一名其他角色回复1点体力。",
  [":xuanhuo__jy__tieqi"] = "当你使用【杀】指定目标后，你可判定，令其本回合一张明置的武将牌非锁定技失效，其需弃置一张与判定结果花色相同的牌，否则其不能使用【闪】抵消此【杀】。",
  [":xuanhuo__jy__liegong"] = "锁定技，你使用【杀】无距离限制且不可被响应。",
  [":xuanhuo__jy__kuanggu"] = "当你对距离1以内的角色造成1点伤害后，你可摸一张牌或回复1点体力。",
  ["#xuanhuo__jy__paoxiaoTrigger"] = "咆哮",
  ["#xuanhuo__longdan_after"] = "龙胆",

  ["#jy__enyuan-give"] = "恩怨：交给 %src 一张手牌，否则失去1点体力",
  ["#jy__xuanhuo-ask"] = "眩惑：弃置一张牌",
  ["@jy__xuanhuo_skills-turn"] = "眩惑",

  ["$jy__enyuan1"] = "伤了我，休想全身而退！",
  ["$jy__enyuan2"] = "报之以李，还之以桃。",
  ["$jy__xuanhuo1"] = "给你的，十倍奉还给我！",
  ["$jy__xuanhuo2"] = "重用许靖，以眩远近。",
  ["~jy__fazheng"] = "汉室复兴，我，是看不到了……",
}

local jy__wangping = General(extension, "jy__wangping", "shu", 4)
jy__wangping:addCompanions("jy__jiangwanfeiyi")
local jy__jianglue = fk.CreateActiveSkill {
  name = "jy__jianglue",
  anim_type = "support",
  frequency = Skill.Limited,
  card_num = 0,
  target_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local targets = table.map(table.filter(room.alive_players, function(p) return H.compareKingdomWith(p, player) end),
      Util.IdMapper)
    room:sortPlayersByAction(targets)
    local num = 0
    for _, p in ipairs(targets) do
      p = room:getPlayerById(p)
      if not p.dead then
        room:changeMaxHp(p, 1)
        if not p.dead then
          if room:recover({
                who = p,
                num = 1,
                recoverBy = player,
                skillName = self.name
              }) then
            num = num + 1
          end
        end
      end
    end
    if num > 0 then player:drawCards(num, self.name) end
  end,
}
jy__wangping:addSkill(jy__jianglue)
Fk:loadTranslationTable {
  ["jy__wangping"] = "王平",
  ["#jy__wangping"] = "键闭剑门",

  ["jy__jianglue"] = "将略",
  [":jy__jianglue"] = "限定技，出牌阶段，你可以所有与你势力相同的角色各加1点体力上限，回复1点体力。然后你摸X张牌（X为与你势力相同的角色数）。",

  ["$jy__jianglue1"] = "奇谋为短，将略为要。",
  ["$jy__jianglue2"] = "为将者，需有谋略。",
  ["~jy__wangping"] = "无当飞军，也有困于深林之时……",
}


local jy__xusheng = General(extension, "jy__xusheng", "wu", 4)
local jy__yicheng = fk.CreateTriggerSkill {
  name = "jy__yicheng",
  anim_type = "defensive",
  events = { fk.TargetConfirmed },
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and H.compareKingdomWith(target, player) and data.card.trueName == "slash" and
        event == fk.TargetConfirmed
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#jy__yicheng-ask::" .. target.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:doIndicate(player.id, { target.id })
    target:drawCards(1, self.name)
    if not target.dead then
      room:askForDiscard(target, 1, 1, true, self.name, false)
    end
  end
}
jy__xusheng:addSkill(jy__yicheng)
jy__xusheng:addCompanions("jy__dingfeng")
Fk:loadTranslationTable {
  ["jy__xusheng"] = "徐盛",
  ["#jy__xusheng"] = "江东的铁壁",

  ["jy__yicheng"] = "疑城",
  [":jy__yicheng"] = "当与你势力相同的角色成为【杀】的目标后，你可令其摸一张牌，然后其弃置一张牌。",

  ["#jy__yicheng-ask"] = "疑城：你可令 %dest 摸一张牌，然后其弃置一张牌",

  ["$jy__yicheng1"] = "不怕死，就尽管放马过来！",
  ["$jy__yicheng2"] = "待末将布下疑城，以退曹贼。",
  ["~jy__xusheng"] = "可怜一身胆略，尽随一抔黄土……",
}

local jy__jiangqin = General(extension, "jy__jiangqin", "wu", 4)
local shangyi = fk.CreateActiveSkill {
  name = 'jy__shangyi',
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = "jy__shangyi",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isKongcheng()
  end,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected == 0 and to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    if player.dead or target.dead or player:isKongcheng() then return end
    U.viewCards(target, player:getCardIds("h"), self.name)
    local choices = {}
    if H.getGeneralsRevealedNum(target) ~= 2 then
      table.insert(choices, "jy__shangyi_hidden")
    end
    if not target:isKongcheng() then
      table.insert(choices, "jy__shangyi_card")
    end
    if #choices == 0 then return end
    local choice = room:askForChoice(player, choices, self.name)
    if choice == "jy__shangyi_hidden" then
      local general = { target:getMark("__heg_general"), target:getMark("__heg_deputy"), target.seat }
      room:askForCustomDialog(player, self.name, "packages/hegemony/qml/KnownBothBox.qml", general)
    elseif choice == "jy__shangyi_card" then
      local card, _ = U.askforChooseCardsAndChoice(player,
        table.filter(target:getCardIds("h"),
          function(id) return Fk:getCardById(id).color == Card.Black or Fk:getCardById(id).color == Card.Red end),
        { "OK" }, self.name, "", nil, 0, 1, target:getCardIds("h"))
      room:throwCard(card, self.name, target, player)
    end
  end,
}
jy__jiangqin:addSkill(shangyi) ----待测试
jy__jiangqin:addCompanions("jy__zhoutai")
Fk:loadTranslationTable {
  ["jy__jiangqin"] = "蒋钦",
  ["#jy__jiangqin"] = "祁奚之器",

  ["jy__shangyi"] = "尚义",
  [":jy__shangyi"] = "出牌阶段限一次，你可令一名其他角色观看你所有手牌，然后你选择一项：1.观看其所有手牌并弃置其中一张牌；2.观看其所有暗置的武将牌",

  ["jy__shangyi_hidden"] = "观看暗置的武将牌",
  ["jy__shangyi_card"] = "观看所有手牌",
  ["#niaoxiang_trigger"] = "鸟翔",

  ["$jy__shangyi1"] = "大丈夫为人坦荡，看下手牌算什么。",
  ["$jy__shangyi2"] = "敌情已了然于胸，即刻出发！",
  ["$jy__niaoxiang1"] = "此战，必是有死无生！",
  ["$jy__niaoxiang2"] = "抢占先机，占尽优势！",
  ["~jy__jiangqin"] = "竟破我阵法...",
}

local sunce = General(extension, "jy__sunce", "wu", 4)
sunce.deputyMaxHpAdjustedValue = -1
sunce:addCompanions { "jy__zhouyu", "jy__taishici", "jy__daqiao" }
local jy__jiang = fk.CreateTriggerSkill {
  name = "jy__jiang",
  anim_type = "drawcard",
  events = { fk.TargetSpecified, fk.TargetConfirmed },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
        ((data.card.trueName == "slash" and data.card.color == Card.Red) or data.card.name == "duel") and
        (event == fk.TargetConfirmed or data.firstTarget)
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,
}
local jy__yingyang = fk.CreateTriggerSkill {
  name = "jy__yingyang",
  events = { fk.PindianCardsDisplayed },
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and (player == data.from or data.results[player.id])
  end,
  on_cost = function(self, event, target, player, data)
    local choice = player.room:askForChoice(player, { 'jy__yingyang_plus3', 'jy__yingyang_sub3', 'Cancel' }, self.name)
    if choice ~= "Cancel" then
      self.cost_data = choice
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    player.room:changePindianNumber(data, player, self.cost_data == "jy__yingyang_plus3" and 3 or -3, self.name)
  end,
}
local jy__hunshang = fk.CreateTriggerSkill {
  name = 'jy__hunshang',
  relate_to_place = 'd',
  events = { fk.EventPhaseStart },
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
        player.phase == Player.Start and player.hp == 1
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:handleAddLoseSkills(player, 'jy__sunce__yingzi|jy__sunce__yinghun')
    room.logic:getCurrentEvent():findParent(GameEvent.Turn):addCleaner(function()
      room:handleAddLoseSkills(player, '-jy__sunce__yingzi|-jy__sunce__yinghun', nil, true, false)
    end)
  end,
}
local yingzi = fk.CreateTriggerSkill {
  name = "jy__sunce__yingzi",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = { fk.DrawNCards },
  on_use = function(self, event, target, player, data)
    data.n = data.n + 1
  end,
}
local yingzi_maxcards = fk.CreateMaxCardsSkill {
  name = "#jy__sunce__yingzi_maxcards",
  fixed_func = function(self, player)
    if player:hasSkill(self) then
      return player.maxHp
    end
  end
}
local yinghun = fk.CreateTriggerSkill {
  name = "jy__sunce__yinghun",
  anim_type = "drawcard",
  mute = true,
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Start and player:isWounded()
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player,
      table.map(player.room:getOtherPlayers(player, false), Util.IdMapper), 1, 1,
      "#yinghun-choose:::" .. player:getLostHp() .. ":" .. player:getLostHp(), self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    local n = player:getLostHp()
    local choice = room:askForChoice(player, { "#yinghun-draw:::" .. n, "#yinghun-discard:::" .. n }, self.name)
    if choice:startsWith("#yinghun-draw") then
      player:broadcastSkillInvoke(self.name, 1)
      room:notifySkillInvoked(player, self.name, "support")
      to:drawCards(n, self.name)
      room:askForDiscard(to, 1, 1, true, self.name, false)
    else
      player:broadcastSkillInvoke(self.name, 2)
      room:notifySkillInvoked(player, self.name, "control")
      to:drawCards(1, self.name)
      room:askForDiscard(to, n, n, true, self.name, false)
    end
  end,
}
sunce:addSkill(jy__jiang)
sunce:addSkill(jy__hunshang)
sunce:addSkill(jy__yingyang)
sunce:addRelatedSkill(yingzi)
sunce:addRelatedSkill(yinghun)
yingzi:addRelatedSkill(yingzi_maxcards)
Fk:loadTranslationTable {
  ['jy__sunce'] = '孙策',
  ["#jy__sunce"] = "江东的小霸王",

  ["jy__jiang"] = "激昂",
  [":jy__jiang"] = "当你使用【决斗】或红色【杀】指定目标后，或成为【决斗】或红色【杀】的目标后，你可以摸一张牌。",
  ['jy__yingyang'] = '鹰扬',
  [':jy__yingyang'] = '当你的拼点牌亮出后，你可令其点数+3或-3。',
  ['jy__hunshang'] = '魂殇',
  [':jy__hunshang'] = '副将技，锁定技，此武将牌减少半个阴阳鱼；准备阶段，若你的体力值为1，你拥有技能“英姿”和“英魂”至本回合结束。',
  ['jy__sunce__yingzi'] = '英姿',
  [":jy__sunce__yingzi"] = "锁定技，摸牌阶段，你多摸一张牌；你的手牌上限等于你的体力上限。",
  ["jy__sunce__yinghun"] = "英魂",
  [":jy__sunce__yinghun"] = "准备阶段，你可选择一名其他角色并选择一项：1.令其摸X张牌，然后弃置一张牌；2.令其摸一张牌，然后弃置X张牌（X为你已损失的体力值）。",

  ["jy__yingyang_plus3"] = "令你的拼点牌点数+3",
  ["jy__yingyang_sub3"] = "令你的拼点牌点数-3",

  ["$jy__jiang1"] = "吾乃江东小霸王孙伯符！",
  ["$jy__jiang2"] = "江东子弟，何惧于天下！",
  ["$jy__yingyang1"] = "此战，我必取胜！",
  ["$jy__yingyang2"] = "相斗之趣，吾常胜之。",
  ["$jy__sunce__yingzi1"] = "公瑾，助我决一死战。",
  ["$jy__sunce__yingzi2"] = "尔等看好了！",
  ["$jy__sunce__yinghun1"] = "父亲，助我背水一战。",
  ["$jy__sunce__yinghun2"] = "孙氏英烈，魂佑江东！",
  ["~jy__sunce"] = "内事不决问张昭，外事不决问周瑜……",
}

local jy__panzhangmazhong = General(extension, "jy__panzhangmazhong", "wu", 4)
local jy__duodao = fk.CreateActiveSkill {
  name = "jy__duodao",
  anim_type = "offensive",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return not player:isKongcheng() and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected == 0 and to_select ~= Self.id and Self:canPindian(Fk:currentRoom():getPlayerById(to_select))
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local pindian = player:pindian({ target }, self.name)
    if pindian.results[target.id].winner == player then
      if player.dead or not #Fk:currentRoom():getPlayerById(target.id):getCardIds("e") > 0 then return end
      local card = room:askForCardChosen(player, target, "e", self.name)
      room:obtainCard(player, card, false, fk.ReasonPrey)
    else
      room:addPlayerMark(player, "jy__duodao_lose-turn", 1)
    end
  end,
}
local duodao_prohibit = fk.CreateProhibitSkill {
  name = "#jy__duodao_prohibit",
  prohibit_use = function(self, player, card)
    return player:getMark("jy__duodao_lose-turn") > 0 and card.trueName == "slash"
  end,
}
local jy__anjian = fk.CreateTriggerSkill {
  name = "jy__anjian",
  anim_type = "offensive",
  events = { fk.TargetSpecified },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.trueName == "slash"
        and not player.room:getPlayerById(data.to):inMyAttackRange(player)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if room:askForChoice(player, { "disresponsive", "jy__anjian_damage" }, self.name, "#jy__anjian-choice:" .. data.to) == "disresponsive" then
      data.disresponsive = true
    else
      data.additionalDamage = (data.additionalDamage or 0) + 1
    end
  end,
}
jy__duodao:addRelatedSkill(duodao_prohibit)
jy__panzhangmazhong:addSkill(jy__anjian)
jy__panzhangmazhong:addSkill(jy__duodao) ---待测试
Fk:loadTranslationTable {
  ["jy__panzhangmazhong"] = "潘璋马忠",
  ["#jy__panzhangmazhong"] = "擒龙伏虎",
  ["designer:jy__panzhangmazhong"] = "官方&江奕",

  ["jy__duodao"] = "夺刀",
  [":jy__duodao"] = "出牌阶段限一次，你可拼点。若你：赢，你获得对方装备区内一张牌；没赢，你本阶段不能使用【杀】。",
  ["jy__anjian"] = "暗箭",
  [":jy__anjian"] = "当你使用【杀】指定目标后，若你不在其攻击范围内，你可令此【杀】不能被其响应或对其造成的伤害+1。",
  ["#jy__anjian-choice"] = "暗箭：令 %src 不能响应此【杀】或受到此【杀】伤害+1",
  ["jy__anjian_damage"] = "伤害+1",

  ["$jy__duodao1"] = "这刀岂是你配用的？",
  ["$jy__duodao2"] = "夺敌兵刃，如断其臂！",
  ["$jy__anjian1"] = "击其懈怠，攻其不备！",
  ["$jy__anjian2"] = "哼，你满身都是破绽！",
  ["~jy__panzhangmazhong"] = "怎么可能，我明明亲手将你……",
}

local lvfan = General(extension, "jy__lvfan", "wu", 3)
local jy__diaodu = fk.CreateTriggerSkill {
  name = "jy__diaodu",
  anim_type = "drawcard",
  events = { fk.CardUsing, fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    if event == fk.CardUsing then
      return H.compareKingdomWith(target, player) and data.card.type == Card.TypeEquip
          and (player:hasShownSkill(self) or player == target)
          and target:getMark("jy__diaodu_use-turn") == 0
    else
      return target == player and target.phase == Player.Play and table.find(player.room.alive_players, function(p)
        return H.compareKingdomWith(p, player) and #p:getCardIds(Player.Equip) > 0
      end)
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUsing then
      return room:askForSkillInvoke(target, self.name, nil, "#jy__diaodu-invoke")
    else
      local targets = table.map(table.filter(room.alive_players, function(p)
        return H.compareKingdomWith(p, player) and #p:getCardIds(Player.Equip) > 0
      end), Util.IdMapper)
      if #targets == 0 then return false end
      local target = room:askForChoosePlayers(player, targets, 1, 1, "#jy__diaodu-choose", self.name, true)
      if #target > 0 then
        self.cost_data = target[1]
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.CardUsing then
      target:drawCards(1, self.name)
      player.room:setPlayerMark(target, "jy__diaodu_use-turn", 1)
    else
      local room = player.room
      local target = room:getPlayerById(self.cost_data)
      local cid = room:askForCardChosen(player, target, "e", self.name)
      room:obtainCard(player, cid, true, fk.ReasonPrey)
      if not table.contains(player:getCardIds(Player.Hand), cid) then return false end
      local card = Fk:getCardById(cid)
      if player.dead then return false end
      local targets = table.map(table.filter(room.alive_players, function(p) return p ~= player and p ~= target end),
        Util.IdMapper)
      -- local to = room:askForChoosePlayers(player, targets, 1, 1, "#jy__diaodu-give:::" .. card:toLogString(), self.name, target ~= player)
      local to = room:askForChoosePlayers(player, targets, 1, 1, "#jy__diaodu-give:::" .. card:toLogString(), self.name,
        true)
      if #to > 0 then
        room:moveCardTo(card, Card.PlayerHand, room:getPlayerById(to[1]), fk.ReasonGive, self.name, nil, true, player.id)
      end
    end
  end,
}
local jy__diancai = fk.CreateTriggerSkill {
  name = "jy__diancai",
  events = { fk.EventPhaseEnd },
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) or target.phase ~= Player.Play or target == player then return false end
    local num = 0
    player.room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
      for _, move in ipairs(e.data) do
        if move and move.from and move.from == player.id and ((move.to and move.to ~= player.id) or not table.contains({ Card.PlayerHand, Card.PlayerEquip }, move.toArea)) then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
              num = num + 1
            end
          end
        end
      end
      return false
    end, Player.HistoryPhase)
    return num >= player.hp
  end,
  on_use = function(self, event, target, player, data)
    local num = player.maxHp - player:getHandcardNum()
    local room = player.room
    if num > 0 then
      player:drawCards(num, self.name)
    end
    if player:getMark("@@jy__diancai_transform") == 0 and room:askForChoice(player, { "transform_deputy", "Cancel" }, self.name) ~= "Cancel" then
      room:setPlayerMark(player, "@@jy__diancai_transform", 1)
      H.transformGeneral(room, player)
    end
  end,
}
lvfan:addSkill(jy__diaodu)
lvfan:addSkill(jy__diancai)
Fk:loadTranslationTable {
  ['jy__lvfan'] = '吕范',
  ["#jy__lvfan"] = "忠笃亮直",

  ['jy__diaodu'] = '调度',
  [':jy__diaodu'] = '①每回合限一次，当与你势力相同的角色使用装备牌时，其可摸一张牌。②出牌阶段开始时，你可获得与你势力相同的一名角色装备区里的一张牌，然后你可将此牌交给另一名角色。',
  ["jy__diancai"] = "典财",
  [":jy__diancai"] = "其他角色的出牌阶段结束时，若你于此阶段失去过不少于X张牌（X为你的体力值），则你可将手牌摸至你体力上限，然后你可变更。",

  ["#jy__diaodu-invoke"] = "调度：你可摸一张牌",
  ["#jy__diaodu-choose"] = "调度：你可获得与你势力相同的一名角色装备区里的一张牌",
  ["#jy__diaodu-give"] = "调度：将%arg交给另一名角色",
  ["#jy__diancai-ask"] = "典财：你可摸 %arg 张牌，然后你可变更副将",

  ["@@jy__diancai_transform"] = "典财 已变更",

  ["$jy__diaodu1"] = "诸军兵器战具，皆由我调配！",
  ["$jy__diaodu2"] = "甲胄兵器，按我所说之法分发！",
  ["$jy__diancai1"] = "军资之用，不可擅作主张！",
  ["$jy__diancai2"] = "善用资财，乃为政上法！",
  ["~jy__lvfan"] = "闻主公欲授大司马之职，容臣不能……谢恩了……",
}

local lingtong = General(extension, "jy__lingtong", "wu", 4)
local jy__xuanlve = fk.CreateTriggerSkill {
  name = "jy__xuanlve",
  anim_type = "control",
  events = { fk.AfterCardsMove },
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return end
    local room = player.room
    for _, move in ipairs(data) do
      if move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerEquip then
            return table.find(room:getOtherPlayers(player, false), function(p)
              return not p:isNude()
            end) ~= nil
          end
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room:getOtherPlayers(player, false), function(p)
      return not p:isNude()
    end)

    targets = table.map(targets, Util.IdMapper)
    local pid = room:askForChoosePlayers(player, targets, 1, 1, '#jy__xuanlve-discard',
      self.name, true)[1]

    if pid then
      self.cost_data = pid
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    local id = room:askForCardChosen(player, to, "he", self.name)
    room:throwCard(id, self.name, to, player)
  end,
}
local jy__yongjin = fk.CreateActiveSkill {
  name = "jy__yongjin",
  anim_type = "offensive",
  frequency = Skill.Limited,
  card_num = 0,
  target_num = 0,
  card_filter = function()
    return false
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    for i = 1, 3, 1 do
      if #room:canMoveCardInBoard("e") == 0 or player.dead then break end
      local to = room:askForChooseToMoveCardInBoard(player, "#jy__yongjin-choose", self.name, true, "e", false)
      if #to == 2 then
        local result = room:askForMoveCardInBoard(player, room:getPlayerById(to[1]), room:getPlayerById(to[2]), self
          .name, "e", nil)
        if not result then
          break
        end
      else
        break
      end
    end
  end,
}
lingtong:addSkill(jy__xuanlve)
lingtong:addSkill(jy__yongjin)
lingtong:addCompanions("jy__ganning")
Fk:loadTranslationTable {
  ['jy__lingtong'] = '凌统',
  ["#jy__lingtong"] = "豪情烈胆",
  ["designer:jy__lingtong"] = "韩旭",

  ['jy__xuanlve'] = '旋略',
  [':jy__xuanlve'] = '当你失去装备区的牌后，你可以弃置一名其他角色的一张牌。',
  ['#jy__xuanlve-discard'] = '旋略：你可以弃置一名其他角色的一张牌',
  ["jy__yongjin"] = "勇进",
  [":jy__yongjin"] = "限定技，出牌阶段，你可依次移动场上至多三张装备牌。" ..
      "<font color='grey'><br />注：可以多次移动同一张牌。",
  ["#jy__yongjin-choose"] = "勇进：你可以移动场上的一张装备牌",

  ["$jy__xuanlve1"] = "舍辎简装，袭掠如风！",
  ["$jy__xuanlve2"] = "卸甲奔袭，摧枯拉朽！",
  ["$jy__yongjin1"] = "急流勇进，覆戈倒甲！",
  ["$jy__yongjin2"] = "长缨缚敌，先登夺旗！",
  ["~jy__lingtong"] = "大丈夫，不惧死亡……",
}

local lukang = General(extension, "jy__lukang", "wu", 3, 3, General.Male)
local keshou = fk.CreateTriggerSkill {
  name = "jy__keshou",
  anim_type = "defensive",
  events = { fk.DamageInflicted },
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player == target and #target:getCardIds("he") > 1
  end,
  on_cost = function(self, event, target, player, data)
    local cards = player.room:askForDiscard(player, 2, 2, true, self.name, true, ".", "#keshou-discard")
    if #cards > 1 then
      self.cost_data = cards
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = self.cost_data
    room:throwCard(cards, self.name, player, player)
    data.damage = data.damage - 1
    local judge = {
      who = player,
      reason = self.name,
      pattern = ".|.|.|.|.|.",
    }
    room:judge(judge)
    if table.every(cards, function(id) return Fk:getCardById(id).color == Card.Red and judge.card.color == Card.Black end) then
      player:drawCards(1, self.name)
    elseif table.every(cards, function(id)
          return Fk:getCardById(id).color == Card.Black and judge.card.color == Card
              .Red
        end) then
      player:drawCards(1, self.name)
    end
  end,
}
local zhuwei = fk.CreateTriggerSkill {
  name = "jy__zhuwei",
  anim_type = "drawcard",
  events = { fk.FinishJudge },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
        and player.room:getCardArea(data.card) == Card.Processing and
        (data.card.trueName == "slash" or data.card.name == "duel")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:obtainCard(player.id, data.card, true, fk.ReasonJustMove)
    local current = room.current
    local choices = { "jy__zhuwei_ask::" .. current.id, "Cancel" }
    if room:askForChoice(player, choices, self.name) ~= "Cancel" then
      room:addPlayerMark(current, "@jy__zhuwei_buff-turn", 1)
      room:addPlayerMark(current, MarkEnum.AddMaxCardsInTurn, 1)
    end
  end,
}
local zhuwei_targetmod = fk.CreateTargetModSkill {
  name = "#jy__zhuwei_targetmod",
  frequency = Skill.Compulsory,
  bypass_times = function(self, player, skill, scope, card, to)
    return card and player:hasSkill(zhengbi) and to:getMark("@@jy__zhengbi_choose-turn") > 0
  end,
  bypass_distances = function(self, player, skill, card, to)
    return card and player:hasSkill(zhengbi) and to:getMark("@@jy__zhengbi_choose-turn") > 0
  end,
}
-- local zhuwei = fk.CreateTriggerSkill{
--   name = "ld__n_zhuwei",
--   anim_type = "drawcard",
--   events = {fk.FinishJudge},
--   can_trigger = function(self, event, target, player, data)
--     return target == player and player:hasSkill(self)
--       and player.room:getCardArea(data.card) == Card.Processing
--   end,
--   on_use = function(self, event, target, player, data)
--     local room = player.room
--     room:obtainCard(player.id, data.card, true, fk.ReasonJustMove)
--     local current = room.current
--     local choices = {"ld__n_zhuwei_ask::" .. current.id, "Cancel"}
--     if room:askForChoice(player, choices, self.name) ~= "Cancel" then
--       room:addPlayerMark(current, "@ld__n_zhuwei_buff-turn", 1)
--       room:addPlayerMark(current, MarkEnum.AddMaxCardsInTurn, 1)
--     end
--   end,
-- }
-- local zhuwei_targetmod = fk.CreateTargetModSkill{
--   name = "#ld__n_zhuwei_targetmod",
--   residue_func = function(self, player, skill, scope)
--     if skill.trueName == "slash_skill" and player:getMark("@ld__n_zhuwei_buff-turn") > 0 and scope == Player.HistoryPhase then
--       return player:getMark("@ld__n_zhuwei_buff-turn")
--     end
--   end,
-- }
lukang:addSkill(keshou)
zhuwei:addRelatedSkill(zhuwei_targetmod)
lukang:addSkill(zhuwei)
Fk:loadTranslationTable {
  ["jy__lukang"] = "陆抗",
  ["#jy__lukang"] = "孤柱扶厦",

  ["jy__keshou"] = "恪守",
  [":jy__keshou"] = "当你受到伤害时，你可弃置两张牌，令此伤害值-1，然后你判定，若结果与你此次弃置的牌颜色均不同，你摸一张牌。",
  ["#keshou-discard"] = "恪守：是否弃置两张牌，令你此次受到的伤害-1",
  ["jy__zhuwei"] = "筑围",
  [":jy__zhuwei"] = "当你的判定牌生效后，若为【杀】或【决斗】，你可获得之。然后你可令当前回合角色手牌上限和使用【杀】的次数上限于此回合内+1。",
  ["jy__zhuwei_ask"] = "令%dest手牌上限和使用【杀】的次数上限于此回合内+1",
  ["@jy__zhuwei_buff-turn"] = "筑围",

  ["$jy__keshou1"] = "仁以待民，自处不败之势。",
  ["$jy__keshou2"] = "宽济百姓，则得战前养备之机。",
  ["$jy__zhuwei1"] = "背水一战，只为破敌。",
  ["$jy__zhuwei2"] = "全线并进，连战克晋。",
  ["~jy__lukang"] = "吾既亡矣，吴又能存几时",
}

local jy__wuguotai = General(extension, "jy__wuguotai", "wu", 3, 3, General.Female)
local jy__ganlu = fk.CreateActiveSkill {
  name = "jy__ganlu",
  anim_type = "control",
  target_num = 2,
  card_num = 0,
  prompt = function()
    return "#jy__ganlu:::" .. Self:getLostHp()
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    if #selected == 0 then
      return #Fk:currentRoom():getPlayerById(to_select).player_cards[Player.Equip] > 0
    elseif #selected == 1 then
      local target1 = Fk:currentRoom():getPlayerById(to_select)
      local target2 = Fk:currentRoom():getPlayerById(selected[1])
      return math.abs(#target1:getCardIds("e") - #target2:getCardIds("e")) <= Self:getLostHp()
    else
      return false
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target1 = room:getPlayerById(effect.tos[1])
    local target2 = room:getPlayerById(effect.tos[2])
    U.swapCards(room, player, target1, target2, target1:getCardIds("e"), target2:getCardIds("e"), self.name,
      Card.PlayerEquip)
  end,
}
local jy__buyi = fk.CreateTriggerSkill {
  name = "jy__buyi",
  anim_type = "support",
  events = { fk.EnterDying },
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and not target:isKongcheng() and
        player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, data, "#jy__buyi-invoke::" .. target.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local id = room:askForCardChosen(player, target, "h", self.name)
    target:showCards({ id })
    if target.dead then return end
    if Fk:getCardById(id).type ~= Card.TypeBasic then
      room:throwCard({ id }, self.name, target, target)
      if target.dead or not target:isWounded() then return end
      room:recover {
        who = target,
        num = 1,
        recoverBy = player,
        skillName = self.name
      }
    end
  end,
}
jy__wuguotai:addSkill(jy__ganlu)
jy__wuguotai:addSkill(jy__buyi)
Fk:loadTranslationTable {
  ["jy__wuguotai"] = "吴国太",
  ["#jy__wuguotai"] = "武烈皇后",

  ["jy__ganlu"] = "甘露",
  [":jy__ganlu"] = "出牌阶段限一次，你可以选择装备区内牌数之差不大于X的两名角色，交换其装备区内的牌（X为你已损失体力值）。",
  ["jy__buyi"] = "补益",
  [":jy__buyi"] = "每回合限一次，当一名角色进入濒死状态时，你可以展示其一张手牌。若此牌不为基本牌，其弃置之，然后回复1点体力。",

  ["#jy__ganlu"] = "甘露：选择装备区内牌数之差不大于%arg的两名角色，交换其装备区内的牌",
  ["#jy__buyi-invoke"] = "补益：你可以展示%dest的一张手牌，若为非基本牌则其弃掉并回复1点体力",

  ["$jy__ganlu1"] = "玄德，实乃佳婿呀！",
  ["$jy__ganlu2"] = "好一个郎才女貌，真是天作之合啊。",
  ["$jy__buyi1"] = "有我在，定保贤婿无余！",
  ["$jy__buyi2"] = "东吴，岂容汝等儿戏！",
  ["~jy__wuguotai"] = "诸位卿家，还请尽力辅佐仲谋啊……",
}

local hetaihou = General(extension, "jy__hetaihou", "qun", 3, 3, General.Female)
local jy__zhendu = fk.CreateTriggerSkill {
  name = "jy__zhendu",
  anim_type = "offensive",
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target.phase == Player.Play and not player:isKongcheng() and not target.dead
  end,
  on_cost = function(self, event, target, player, data)
    local prompt = (target == player) and "#jy__zhendu-self" or "#jy__zhendu-invoke::" .. target.id
    local card = player.room:askForDiscard(player, 1, 1, false, self.name, true, ".", prompt, true)
    if #card > 0 then
      player.room:doIndicate(player.id, { target.id })
      self.cost_data = { tos = { target.id }, cards = card }
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data.cards, self.name, player, player)
    if not target.dead and target:canUseTo(Fk:cloneCard("analeptic"), target) then
      room:useVirtualCard("analeptic", nil, target, target, self.name, false)
    end
    if player ~= target and not target.dead then
      room:damage {
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
      }
    end
  end,
}
local jy__qiluan = fk.CreateTriggerSkill {
  name = "jy__qiluan",
  anim_type = "offensive",
  events = { fk.TurnEnd },
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      local logic = player.room.logic
      local deathevents = logic.event_recorder[GameEvent.Death] or Util.DummyTable
      local turnevents = logic.event_recorder[GameEvent.Turn] or Util.DummyTable
      return #deathevents > 0 and #turnevents > 0 and deathevents[#deathevents].id > turnevents[#turnevents].id
    end
  end,
  on_use = function(self, event, target, player, data)
    local x = 0
    player.room.logic:getEventsOfScope(GameEvent.Death, 1, function(e)
      local deathData = e.data[1]
      if deathData.damage and deathData.damage.from == player then
        x = x + 3
      else
        x = x + 1
      end
      return false
    end, Player.HistoryTurn)
    if x > 0 then
      player:drawCards(x, self.name)
    end
  end,
}
hetaihou:addSkill(jy__zhendu)
hetaihou:addSkill(jy__qiluan)
Fk:loadTranslationTable {
  ["jy__hetaihou"] = "何太后",
  ["#jy__hetaihou"] = "弄权之蛇蝎",

  ["jy__zhendu"] = "鸩毒",
  [":jy__zhendu"] = "一名角色的出牌阶段开始时，你可以弃置一张手牌。若如此做，该角色视为使用一张【酒】，然后若该角色不为你，你对其造成1点伤害。",
  ["jy__qiluan"] = "戚乱",
  [":jy__qiluan"] = "一名角色回合结束时，你可摸X张牌（X为本回合死亡的角色数，其中每有一名角色是你杀死的，你多摸两张牌）。",
  ["#jy__zhendu-invoke"] = "鸩毒：你可以弃置一张手牌视为 %dest 使用一张【酒】，然后你对其造成1点伤害",
  ["#jy__zhendu-self"] = "鸩毒：你可以弃置一张手牌视为使用一张【酒】",

  ["$jy__zhendu1"] = "怪只怪你，不该生有皇子！",
  ["$jy__zhendu2"] = "后宫之中，岂有你的位置！",
  ["$jy__qiluan1"] = "待我召吾兄入宫，谁敢不从？",
  ["$jy__qiluan2"] = "本后自有哥哥在外照应，有什么好担心的！",
  ["~jy__hetaihou"] = "你们男人造的孽，非要说什么红颜祸水……",
}

local yuji = General(extension, "jy__yuji", "qun", 3)
local jy__qianhuan = fk.CreateTriggerSkill {
  name = "jy__qianhuan",
  events = { fk.Damaged, fk.TargetConfirming, fk.BeforeCardsMove },
  anim_type = "defensive",
  derived_piles = "yuji_sorcery",
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    if event == fk.Damaged then
      return not target.dead and H.compareKingdomWith(target, player) and not player:isNude() and
          #player:getPile("yuji_sorcery") < 4
    elseif event == fk.TargetConfirming then
      return H.compareKingdomWith(target, player) and #player:getPile("yuji_sorcery") > 0 and
          (data.card.type == Card.TypeBasic or data.card:isCommonTrick()) and #AimGroup:getAllTargets(data.tos) == 1
    elseif event == fk.BeforeCardsMove then
      for _, move in ipairs(data) do
        if move.to ~= nil and move.toArea == Card.PlayerJudge then
          local friend = player.room:getPlayerById(move.to)
          return H.compareKingdomWith(friend, player) and #move.moveInfo > 0 and #player:getPile("yuji_sorcery") > 0
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local card = {}
    local room = player.room
    if event == fk.Damaged then
      local suits = {}
      for _, id in ipairs(player:getPile("yuji_sorcery")) do
        table.insert(suits, Fk:getCardById(id):getSuitString())
      end
      suits = table.concat(suits, ",")
      card = room:askForCard(player, 1, 1, true, self.name, true, ".|.|^(" .. suits .. ")", "#jy__qianhuan-dmg",
        "yuji_sorcery")
    elseif event == fk.TargetConfirming then
      card = room:askForCard(player, 1, 1, false, self.name, true, ".|.|.|yuji_sorcery",
        "#jy__qianhuan-def::" .. target.id .. ":" .. data.card:toLogString(), "yuji_sorcery")
    elseif event == fk.BeforeCardsMove then
      local delayed_trick = nil
      local friend = nil
      for _, move in ipairs(data) do
        if move.to ~= nil and move.toArea == Card.PlayerJudge then
          friend = move.to
          for _, info in ipairs(move.moveInfo) do
            local id = info.cardId
            local source = player
            if info.fromArea == Card.PlayerJudge then
              source = room:getPlayerById(move.from) or player
            end
            delayed_trick = source:getVirualEquip(id)
            if delayed_trick == nil then delayed_trick = Fk:getCardById(id) end
            break
          end
          if delayed_trick then break end
        end
      end
      if delayed_trick then
        card = player.room:askForCard(player, 1, 1, false, self.name, true, ".|.|.|yuji_sorcery",
          "#jy__qianhuan-def::" .. friend .. ":" .. delayed_trick:toLogString(), "yuji_sorcery")
      end
    end
    if #card > 0 then
      self.cost_data = card
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke("jy__qianhuan")
    if event == fk.Damaged then
      room:notifySkillInvoked(player, "jy__qianhuan", "masochism")
      player:addToPile("yuji_sorcery", self.cost_data, true, self.name)
    elseif event == fk.TargetConfirming then
      room:notifySkillInvoked(player, "jy__qianhuan", "defensive")
      room:moveCardTo(self.cost_data, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, self.name, "yuji_sorcery")
      AimGroup:cancelTarget(data, target.id)
      return true
    elseif event == fk.BeforeCardsMove then
      room:moveCardTo(self.cost_data, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, self.name, "yuji_sorcery")
      local mirror_moves = {}
      local ids = {}
      for _, move in ipairs(data) do
        if move.toArea == Card.PlayerJudge then
          local move_info = {}
          local mirror_info = {}
          for _, info in ipairs(move.moveInfo) do
            local id = info.cardId
            table.insert(mirror_info, info)
            table.insert(ids, id)
          end
          if #mirror_info > 0 then
            move.moveInfo = move_info
            local mirror_move = table.clone(move)
            mirror_move.to = nil
            mirror_move.toArea = Card.DiscardPile
            mirror_move.moveInfo = mirror_info
            table.insert(mirror_moves, mirror_move)
          end
        end
      end
      table.insertTable(data, mirror_moves)
    end
  end,
}
yuji:addSkill(jy__qianhuan)
Fk:loadTranslationTable {
  ["jy__yuji"] = "于吉",
  ["#jy__yuji"] = "魂绕左右",
  ["designer:jy__yuji"] = "淬毒",
  ["illustrator:jy__yuji"] = "G.G.G.",

  ["jy__qianhuan"] = "千幻",
  [":jy__qianhuan"] = "①当与你势力相同的角色受到伤害后，你可将一张与你武将牌上花色均不同的牌置于你的武将牌上（称为“幻”）。②当与你势力相同的角色成为基本牌或锦囊牌的唯一目标时，你可将一张“幻”置入弃牌堆，取消此目标。",

  ["#jy__qianhuan-dmg"] = "千幻：你可一张与“幻”花色均不同的牌置于你的武将牌上（称为“幻”）",
  ["#jy__qianhuan-def"] = "千幻：你可一张“幻”置入弃牌堆，取消%arg的目标 %dest",
  ["yuji_sorcery"] = "幻",

  ["$jy__qianhuan1"] = "幻化于阴阳，藏匿于乾坤。",
  ["$jy__qianhuan2"] = "幻变迷踪，虽飞鸟亦难觅踪迹。",
  ["~jy__yuji"] = "幻化之物，终是算不得真呐。",
}

local dongzhuo = General(extension, "jy__dongzhuo", "qun", 4)
local hengzheng = fk.CreateTriggerSkill {
  name = 'jy__hengzheng',
  anim_type = "big", -- 神杀特色
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Draw and
        (player.hp == 1 or player:isKongcheng()) and
        table.find(player.room:getOtherPlayers(player, false), function(p) return not p:isAllNude() end)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(room:getOtherPlayers(player, true)) do
      if not p:isAllNude() then
        local id = room:askForCardChosen(player, p, "hej", self.name)
        room:obtainCard(player, id, false)
      end
    end
    return true
  end,
}
local benghuai = fk.CreateTriggerSkill {
  name = "jy__benghuai",
  anim_type = "negative",
  frequency = Skill.Compulsory,
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish and
        table.find(player.room.alive_players, function(p) return p.hp < player.hp end)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choice = room:askForChoice(player, { "loseMaxHp", "loseHp" }, self.name)
    if choice == "loseMaxHp" then
      room:changeMaxHp(player, -1)
    else
      room:loseHp(player, 1, self.name)
    end
  end,
}

local baoling = fk.CreateTriggerSkill {
  name = "jy__baoling",
  relate_to_place = 'm',
  anim_type = "big",
  events = { fk.EventPhaseEnd },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play and H.hasGeneral(player, true)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    H.removeGeneral(room, player, true)
    room:changeMaxHp(player, 3)
    room:recover {
      who = player,
      num = 3,
      skillName = self.name
    }
    room:handleAddLoseSkills(player, benghuai.name)
  end,
}
dongzhuo:addSkill(hengzheng)
dongzhuo:addSkill(baoling)
dongzhuo:addRelatedSkill(benghuai)
Fk:loadTranslationTable {
  ['jy__dongzhuo'] = '董卓',
  ["#jy__dongzhuo"] = "魔王",

  ['jy__hengzheng'] = '横征',
  [':jy__hengzheng'] = '摸牌阶段，若你体力值为1或者没有手牌，你可改为获得所有其他角色区域内各一张牌。',
  ['jy__baoling'] = '暴凌',
  [':jy__baoling'] = '主将技，出牌阶段结束时，若你有副将，你移除副将，加3点体力上限并回复3点体力，然后获得〖崩坏〗。',
  ['jy__benghuai'] = '崩坏',
  [':jy__benghuai'] = '锁定技，结束阶段，若你不是体力值最小的角色，你失去1点体力或减1点体力上限。',

  ['$jy__hengzheng1'] = '老夫进京平乱，岂能空手而归？',
  ['$jy__hengzheng2'] = '谁的？都是我的！',
  ['$jy__baoling1'] = '大丈夫，岂能妇人之仁？',
  ['$jy__baoling2'] = '待吾大开杀戒，哈哈哈哈！',
  ['~jy__dongzhuo'] = '为何人人……皆与我为敌？',
}

local zhangren = General(extension, "jy__zhangren", "qun", 4)
zhangren:addCompanions("jy__zhangxiu")
local jy__chuanxin = fk.CreateTriggerSkill {
  name = "jy__chuanxin",
  anim_type = "offensive",
  events = { fk.DamageCaused },
  can_trigger = function(self, event, target, player, data)
    return target == player and target:hasSkill(self) and data.card and
        table.contains({ "slash", "duel" }, data.card.trueName) and not data.chain
        and H.compareExpectedKingdomWith(player, data.to, true)
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, data, "#jy__chuanxin-ask::" .. data.to.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local target = data.to
    if H.hasGeneral(target, true) then
      H.removeGeneral(room, target, true)
    end
    room:loseHp(target, 1, self.name)
    return true
  end,
}
zhangren:addSkill(jy__chuanxin)
Fk:loadTranslationTable {
  ['jy__zhangren'] = '张任',
  ["#jy__zhangren"] = "索命神射",

  ['jy__chuanxin'] = '穿心',
  [':jy__chuanxin'] = '当你使用【杀】或【决斗】造成伤害时，若目标角色与你势力不同或你明置此武将牌后与其势力不同，你可防止此伤害。然后若其:有副将，你移除其副将，然后其失去1点体力；无副将，其失去1点体力。',
  ["#jy__chuanxin-ask"] = "穿心：你可以防止%dest受到1点伤害，移除其副将，然后其失去1点体力",

  ['$jy__chuanxin1'] = '一箭穿心，哪里可逃？',
  ['$jy__chuanxin2'] = '穿心之痛，细细品吧，哈哈哈哈！',
  ['~jy__zhangren'] = '本将军败于诸葛，无憾……',
}

local lijueguosi = General(extension, "jy__lijueguosi", "qun", 4)
lijueguosi:addCompanions("jy__jiaxu")
local jy__xiongsuan = fk.CreateActiveSkill {
  name = "jy__xiongsuan",
  anim_type = "offensive",
  frequency = Skill.Limited,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  card_num = 1,
  target_num = 1,
  card_filter = function(self, to_select, selected)
    return #selected < 1 and Fk:currentRoom():getCardArea(to_select) == Player.Hand
  end,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and H.compareKingdomWith(Fk:currentRoom():getPlayerById(to_select), Self)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:throwCard(effect.cards, self.name, player, player)
    if player.dead or target.dead then return false end
    room:damage {
      from = player,
      to = target,
      damage = 1,
      skillName = self.name,
    }
    if player.dead then return false end
    player:drawCards(3, self.name)
    if target.dead then return false end
    local skills = table.filter(target.player_skills, function(s)
      return s.frequency == Skill.Limited and target:usedSkillTimes(s.name, Player.HistoryGame) > 0
    end)
    if #skills == 0 then return false end
    local skillNames = table.map(skills, function(s)
      return s.name
    end)
    local skill = room:askForChoice(player, skillNames, self.name, "#jy__xiongsuan-reset::" .. target.id)
    room:setPlayerMark(player, "_jy__xiongsuan-turn", { skill, target.id })
  end,
}
local jy__xiongsuan_delay = fk.CreateTriggerSkill {
  name = "#jy__xiongsuanDelay",
  visible = false,
  frequency = Skill.Compulsory,
  events = { fk.TurnEnd },
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and type(player:getMark("_jy__xiongsuan-turn")) == "table"
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local skill = player:getMark("_jy__xiongsuan-turn")[1]
    target = room:getPlayerById(player:getMark("_jy__xiongsuan-turn")[2])
    target:addSkillUseHistory(skill, -1)
    room:sendLog {
      type = "#jy__xiongsuanReset",
      from = target.id,
      arg = skill,
    }
  end,
}
jy__xiongsuan:addRelatedSkill(jy__xiongsuan_delay)
lijueguosi:addSkill(jy__xiongsuan)
Fk:loadTranslationTable {
  ['jy__lijueguosi'] = '李傕郭汜',
  ["#jy__lijueguosi"] = "犯祚倾祸",

  ["jy__xiongsuan"] = "凶算",
  [":jy__xiongsuan"] = "限定技，出牌阶段，你可弃置一张手牌并选择与你势力相同的一名角色，你对其造成1点伤害，摸三张牌，选择其一个已发动过的限定技，然后此回合结束后，你令此技能于此局游戏内的发动次数上限+1。",
  ["#jy__xiongsuan-reset"] = "凶算：请重置%dest的一项技能",
  ["#jy__xiongsuanDelay"] = "凶算",
  ["#jy__xiongsuanReset"] = "%from 重置了限定技“%arg”",

  ["$jy__xiongsuan1"] = "此战虽凶，得益颇高。",
  ["$jy__xiongsuan2"] = "谋算计策，吾二人尚有险招。",
  ["~jy__lijueguosi"] = "异心相争，兵败战损……",
}

local jy__yuanshu = General(extension, "jy__yuanshu", "qun", 4)
local jy__yongsi = fk.CreateTriggerSkill {
  name = "jy__yongsi",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = { fk.DrawNCards, fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.EventPhaseStart then
        return player.phase == Player.Discard
      end
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.DrawNCards then
      data.n = data.n + 2
    else
      player.room:askForDiscard(player, 2, 2, true, self.name, false, ".", "#jy__yongsi-discard")
    end
  end,
}
jy__yuanshu:addSkill(jy__yongsi)
Fk:loadTranslationTable {
  ["jy__yuanshu"] = "袁术",
  ["#jy__yuanshu"] = "仲家帝",

  ["jy__yongsi"] = "庸肆",
  [":jy__yongsi"] = "锁定技，摸牌阶段，你额外摸两张牌。弃牌阶段开始时，你弃置两张牌（不足则全弃）。",

  ["#jy__yongsi-discard"] = "庸肆：你须弃置两张牌",

  ["$jy__yongsi1"] = "大汉天下，已半入我手！",
  ["$jy__yongsi2"] = "玉玺在手，天下我有！",
  ["$weidi1"] = "你们都得听我的号令！",
  ["$weidi2"] = "我才是皇帝！",
  ["~jy__yuanshu"] = "可恶！就差……一步了……",
}

local zhangxiu = General(extension, "jy__zhangxiu", "qun", 4)
local fudi = fk.CreateTriggerSkill {
  name = 'jy__fudi',
  events = { fk.Damaged },
  anim_type = "masochism",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.from and data.from ~= player and not player:isKongcheng()
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local c = room:askForCard(player, 1, 1, false, self.name, true,
      '.|.|.|hand', '#jy__fudi-give:' .. data.from.id)[1]
    if c then
      self.cost_data = c
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:obtainCard(data.from, self.cost_data, false, fk.ReasonGive)
    local p = data.from
    local x = player.hp
    if not p or p.dead then return end
    local targets = {}
    for _, _p in ipairs(room.alive_players) do
      if H.compareKingdomWith(_p, p) and _p.hp >= x then
        table.insert(targets, _p)
      end
    end
    local to
    if #targets == 0 then
      return
    elseif #targets == 1 then
      to = targets[1].id
    else
      to = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper),
        1, 1, '#jy__fudi-dmg', self.name, false)[1]
    end
    room:damage {
      from = player,
      to = room:getPlayerById(to),
      damage = 2,
      skillName = self.name,
    }
  end,
}
zhangxiu:addSkill(fudi)
zhangxiu:addCompanions("jy__jiaxu")
Fk:loadTranslationTable {
  ['jy__zhangxiu'] = '张绣',
  ["#jy__zhangxiu"] = "北地枪王",

  ['jy__fudi'] = '附敌',
  [':jy__fudi'] = '当你受到其他角色造成的伤害后，你可以交给伤害来源一张手牌。若如此做，你对与其势力相同的角色中体力值不小于你的一名角色造成2点伤害。',
  ['#jy__fudi-give'] = '附敌：你可以交给 %src 一张手牌，然后对其势力体力最大造成2点伤害',
  ['#jy__fudi-dmg'] = '附敌：选择要造成伤害的目标',

  ['$jy__fudi1'] = '弃暗投明，为明公计！',
  ['$jy__fudi2'] = '绣虽有降心，奈何贵营难容。',
  ['~jy__zhangxiu'] = '若失文和，吾将何归？',
}

-- local zuoci = General(extension, "jy__zuoci", "qun", 3)
-- ---@param player ServerPlayer
-- ---@param skillName string
-- local addFangkeSkill = function(player, skillName)
--   local room = player.room
--   local skill = Fk.skills[skillName]
--   if (not skill) or skill.lordSkill or skill.switchSkillName
--       or skill.frequency > 2 or skill.relate_to_place == "m" or skill.relate_to_place == "d"
--       or player:hasSkill(skill) then
--     return
--   end

--   room:addTableMark(player, "jy__xing_skills", skillName)
--   player:addFakeSkill(skill)
--   player:prelightSkill(skill, true)
-- end

-- ---@param player ServerPlayer
-- ---@param skillName string
-- local removeFangkeSkill = function(player, skillName)
--   local room = player.room
--   local skill = Fk.skills[skillName]
--   room:removeTableMark(player, "jy__xing_skills", skillName)
--   player:loseFakeSkill(skill)
-- end

-- ---@param player ServerPlayer
-- ---@param general General
-- ---@param addSkill bool
-- local function addFangke(player, general, addSkill)
--   local room = player.room
--   local glist = player:getMark("@&jy__xing")
--   if glist == 0 then glist = {} end
--   table.insertIfNeed(glist, general.name)
--   room:setPlayerMark(player, "@&jy__xing", glist)

--   if not addSkill then return end
--   for _, s in ipairs(general.skills) do
--     addFangkeSkill(player, s.name)
--   end
--   for _, sname in ipairs(general.other_skills) do
--     addFangkeSkill(player, sname)
--   end
-- end

-- ---@param player ServerPlayer
-- ---@param general string
-- local function removeFangke(player, general)
--   local room = player.room
--   local glist = player:getTableMark("@&jy__xing")
--   if table.removeOne(glist, general) then
--     if #glist == 0 then glist = 0 end
--     room:setPlayerMark(player, "@&jy__xing", glist)
--     for _, sname in ipairs(Fk.generals[general]:getSkillNameList()) do
--       removeFangkeSkill(player, sname)
--     end
--   end
-- end

-- local xinsheng = fk.CreateTriggerSkill {
--   name = "jy__xinsheng",
--   events = { fk.EventPhaseStart, fk.Damaged, fk.GeneralRevealed },
--   can_trigger = function(self, event, target, player, _)
--     if not (target == player and player:hasSkill(self)) then return end
--     return event == fk.Damaged or player.phase == Player.Start or event == fk.GeneralRevealed
--   end,
--   on_use = function(self, event, _, player, _)
--     local room = player.room
--     local generals = {}
--     if event == fk.EventPhaseStart or event == fk.GeneralRevealed then
--       if player:getMark("@&jy__xing") == 0 or #player:getMark("@&jy__xing") < 2 then
--         generals = room:getNGenerals(2)
--       else
--         -- local choices = player:getMark("@&jy__xing")
--         -- local remove_list = {}
--         -- local result = room:askForCustomDialog(player, self.name,
--         --   "packages/utility/qml/ChooseGeneralsAndChoiceBox.qml", {
--         --     choices,
--         --     { "OK" },
--         --     "#jy__xinshen_xing_recast",
--         --     {},
--         --     0,
--         --     2,
--         --   })
--         -- if result ~= "" then
--         --   local reply = json.decode(result)
--         --   remove_list = reply.cards or {}
--         -- else
--         --   -- 默认不移除任何“形”
--         --   remove_list = {}
--         -- end
--         -- for _, choice in ipairs(remove_list) do
--         --   removeFangke(player, choice)
--         -- end
--         -- generals = room:getNGenerals(#remove_list)
--         local choices = player:getMark("@&jy__xing")
--         local choice
--         local result = room:askForCustomDialog(player, self.name,
--           "packages/utility/qml/ChooseGeneralsAndChoiceBox.qml", {
--             choices,
--             { "OK" },
--             "#jy__xinshen_xing_recast",
--             -- {},
--             -- 0,
--             -- 2,
--           })
--         if result ~= "" then
--           local reply = json.decode(result)
--           choice = reply.cards[1]
--         else
--           choice = table.random(choices) ---@type string
--         end
--         removeFangke(player, choice)
--         generals = room:getNGenerals(1)
--       end
--     else
--       generals = room:getNGenerals(1)
--     end
--     table.forEach(generals, function(g) addFangke(player, Fk.generals[g], true) end)
--   end,

--   refresh_events = { fk.EventLoseSkill, fk.GeneralHidden, fk.BuryVictim },
--   can_refresh = function(self, event, target, player, data)
--     if player:getMark("@&jy__xing") == 0 or player ~= target then return false end
--     if event == fk.EventLoseSkill then
--       return data == self
--     elseif event == fk.BuryVictim then
--       return true
--     elseif event == fk.GeneralHidden then
--       return table.contains(Fk.generals[data]:getSkillNameList(), self.name)
--     end
--   end,
--   on_refresh = function(self, event, target, player, data)
--     local record = table.simpleClone(player:getMark("@&jy__xing"))
--     for _, s in ipairs(record) do
--       removeFangke(player, s)
--     end
--   end,
-- }

-- local huashen = fk.CreateTriggerSkill {
--   name = "jy__huashen",
--   events = { fk.AfterSkillEffect },
--   can_trigger = function(self, _, target, player, data)
--     return target == player and player:hasSkill(self) and
--         table.contains(player:getTableMark("jy__xing_skills"), data.name)
--   end,
--   on_cost = Util.TrueFunc,
--   on_use = function(self, _, target, player, data)
--     local all_xing = player:getMark("@&jy__xing")
--     local choices = {}
--     for _, s in ipairs(all_xing) do
--       local general = Fk.generals[s]
--       local skills = general:getSkillNameList()
--       if table.contains(skills, data.name) then
--         table.insert(choices, s)
--       end
--     end
--     local choice = player.room:askForChoice(player, choices, self.name, "#jy__huashen_remove")
--     removeFangke(player, choice)
--   end,
-- }

-- zuoci:addCompanions("jy__yuji")
-- zuoci:addSkill(xinsheng)
-- zuoci:addSkill(huashen)
-- Fk:loadTranslationTable {
--   ["jy__zuoci"] = "左慈",
--   ["#jy__zuoci"] = "鬼影神道",
--   ["illustrator:jy__zuoci"] = "吕阳",
--   ["jy__huashen"] = "化身",
--   [":jy__huashen"] = "当你需要发动“形”拥有的技能时，你可以于对应的时机发动“形”拥有的一个无技能标签的技能，然后于此技能结算后将拥有此技能的“形”置入武将牌堆。<br><font color = 'grey'>注：状态技（方片杀无距离）、获得状态的技能（天义）不可用。</font>",
--   ["jy__xinsheng"] = "新生",
--   [":jy__xinsheng"] = "准备阶段，若你的“形”：少于两张，你可以观看武将牌堆中的随机五张武将牌，选择其中的两张置于你的武将牌上（称为“形”）；不少于两张，你可以将一张“形”置入武将牌堆，然后随机将武将牌堆中的一张武将牌置于你的武将牌上（称为“形”）。" ..
--       "当你受到伤害后，你可以随机将武将牌堆中的一张武将牌置于你的武将牌上（称为“形”）。",

--   ["@&jy__xing"] = "形",

--   ["#jy__xinshen_xing1"] = "新生：选择一张武将牌置于你的武将牌上，称为“形”",
--   ["#jy__xinshen_xing2"] = "新生：选择两张武将牌置于你的武将牌上，称为“形”",
--   ["#jy__xinshen_xing_recast"] = "新生：移去一张“形”，然后随机将一张武将牌置于你的武将牌上，称为“形”",
--   ["#jy__huashen_remove"] = "化身：移去一张“形”",

--   ["$jy__huashen1"] = "世间万物，贫道皆可化为其形。",
--   ["$jy__huashen2"] = "尘身土塑，唯魂魄难得。",
--   ["$jy__xinsheng1"] = "大成若缺，损益无妨。",
--   ["$jy__xinsheng2"] = "大盈若冲，心神自现。",
--   ["~jy__zuoci"] = "仙人之逝，魂归九天…",
-- }
local zuoci = General(extension, "jy__zuoci", "qun", 3)
local huashen = fk.CreateActiveSkill {
  name = "jy__huashen",
  anim_type = "offensive",
  prompt = "#jy__huashen",
  card_num = 0,
  target_num = 0,
  can_use = function(self, player)
    return player:getMark("jy__huashen-phase") == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:addPlayerMark(player, "jy__huashen-phase", 1)
    H.transformGeneral(room, player)
  end,
}
local huashen_trigger = fk.CreateTriggerSkill {
  name = "#jy__huashen_trigger",
  mute = true,
  events = { fk.Damaged },
  main_skill = huashen,
  on_use = function(self, event, target, player, data)
    local room = player.room
    H.transformGeneral(room, player)
  end,
}
zuoci:addSkill(huashen)
huashen:addRelatedSkill(huashen_trigger)
Fk:loadTranslationTable {
  ["jy__zuoci"] = "左慈",
  ["#jy__zuoci"] = "鬼影神道",

  ["jy__huashen"] = "化身",
  ["#jy__huashen_trigger"] = "化身",
  [":jy__huashen"] = "出牌阶段限一次或当你受到伤害后，你可以变更副将（无次数限制）。",

  ["#jy__huashen"] = "你可以变更副将（无次数限制）",


  ["$jy__huashen1"] = "世间万物，贫道皆可化为其形。",
  ["$jy__huashen2"] = "尘身土塑，唯魂魄难得。",
  ["~jy__zuoci"] = "仙人之逝，魂归九天…",
}
return extension
